How to create a JSON web token in an Express API

Create a JWT and send it back to the browser

In the last article, we have seen what a JSON web token (JWT) is, and why we may want to use one. Now let's learn how to actually generate a token.

Several Node libraries provide help in creating and managing web tokens. We will use a Node module called jsonwebtoken in our projects. Let's install it:

yarn add jsonwebtoken

To get our feet wet with web tokens in an Express application, we'll create an endpoint that, when called, simply sends back a token to the client.

Our purpose at this point is just to demonstrate how a token is generated and how it's sent back to the browser that makes the request.
We don't need the token to do anything special right now, or have any particular information in it.

In our example, we'll start by defining a /token endpoint in the server.js file. This is the endpoint that sends a token back to the client:

server.get('/token', (req, res) => {
  res.send(token)
})

As it stands, our code won't work, because we haven't defined a token yet. But how do we create a token? Let's look at the documentation in the jsonwebtoken module.

In the documentation we notice under Usage that we can generate a token by using the .sign() method defined on the jsonwebtoken object.
This method takes some arguments: a payload, a secret string and a series of optional parameters.

The payload is in the form of a Javascript object. We will use this simple object for our test:

{
  subject: "user",
  username: "cesare",
  favoriteColor: "blue"
}

This payload object will be converted to a properly formatted JSON string by the .sign() method.

If you remember when we talked about JWT structure, we said that the secret is a string, known only to our server, that is added to the token payload and header in order to create a unique salted hash.

For now we will just hardcode a simple string inside our endpoint. In the final implementation the secret should come from a more secure place, like an environment variable for example.

For the options arguments, we'll create another object with an expiration date for our token: 1 hour.

With these details established, let's finish up our code:

server.get('/token', (req, res) => {
  const payload = {
    subject: "user",
    username: "cesare",
    favoriteColor: "blue"
  };

  const secret = "Secret"

  const options = {
    expiresIn: '1h'
  }

  const token = jwt.sign(payload, secret, options);

  res.json(token)
})

If we test this endpoint in Postman now, and we send a GET request to localhost:5000/token, we'll get back a token:

And if we paste the token in the JWT.io tool, we can see the data we have encoded inside the token:


In this article, we have seen how to create a JSON web token and how to send it back to the browser. We'll explore more about JWTs in the following articles.


Did you like this article? Share it with your friends.
I write daily about front-end and back-end web technologies.
You can receive all my articles in your inbox by subscribing to my newsletter. Just click the button below. No spam, just good, useful content. Guaranteed!
Follow me on Twitter