Node.js: how to create and serve a JSON Web Token (JWT) with ExpressJS

Node.js: how to create and serve a JSON Web Token (JWT) with ExpressJS

In Node.js, one can create and serve a JWT using the jsonwebtoken module together with the ExpressJS framework.

A JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compact and secure way to transmit information between parties as a digitally signed JSON object. In Node.js, one can create and serve a JWT using the jsonwebtoken module together with the ExpressJS framework.

To get started, you need to install the jsonwebtoken module by running the command npm install jsonwebtoken in the terminal console. Next, you need to import the module into a JavaScript file and define a secret key for signing the JWT.


const jwt = require('jsonwebtoken');
const secretKey = 'my_secret_key';

Later, you can create a JWT with the data you want to include in the token, using the sign() method of the jsonwebtoken module.


'use strict';

const userData = { 
  name: 'John Doe',
  email: 'johndoe@email.com',
  role: 'user'
};

const token = jwt.sign(userData, secretKey, { expiresIn: '1h' });

The created JWT will contain the data specified in the userData variable, signed with the secret key secretKey and with a validity duration of one hour.

To serve the JWT via ExpressJS, you need to create an API that returns the token as an HTTP response. For example:


'use strict';

const express = require('express');
const app = express();

app.get('/api/token', (req, res) => {
  const token = jwt.sign(userData, secretKey, { expiresIn: '1h' });
  res.json({ token });
});

app.listen(3000, () => {
  console.log('Server running on port 3000');
});

In this example, a GET API endpoint is created that returns the JWT as a JSON object with the token property. When you call this API through your browser or an application, you will receive a JWT that is valid for one hour.

In summary, creating and serving a JWT in Node.js via ExpressJS is a relatively simple process that requires only a few lines of code using the 'jsonwebtoken' package. Once the token is created, it can be included in an HTTP request as an Authorization header or in a cookie, to authenticate the user in a web or mobile application.