Skip to content

How to use JWT (JSON Web Token) with Express JS

Last updated on September 7, 2017

Today I am gonna show you JWT(JSON Web Token) token generating and verification steps with express JS framework.

What is JWT (JSON Web Token)?

A JSON Web Token, or JWT, is used to send information that can be verified and trusted by means of a digital signature. It comprises a compact and URL-safe JSON object, which is cryptographically signed to verify its authenticity, and which can also be encrypted if the payload contains sensitive information. Because of it’s compact structure, JWT is usually used in HTTP Authorization headers or URL query parameters. How to use JWT Express JS

Lets integrate JWT with Express JS

Create project directory and install required dependencies with below shown commands.

   $ mkdir express-jwt-demo
   $ cd express-jwt-demo
   $ npm init --yes
   $ npm install --save express body-parser jsonwebtoken
  • mkdir express-jwt-demo – it will crate a folder called “express-jwt-demo
  • cd express-jwt-demo – changing directory to “express-jwt-demo
  • npm init –yes – will create package.json file under the current directory
  • npm install –save express body-parser jsonwebtoken – it will download all mentioned modules into node_modules directory

What do these packages do?

  • express is the Node framework.
  • body-parser will let us pull POST content from our HTTP request.
  • jsonwebtoken is a library which will take care of generating and verifying

Now lets setup application, create a file called server.js with below code, go though the comments of the code for better understanding.

// server.js
// importing express 
const express = require('express');
// creating express instance
const app = express();

// importing body-parser, which will handle the user input bodies
const bodyParser = require('body-parser');

// importing jsonwebtoken module, this module will create and decode the JWT tokens.
const jsonWebToken = require('jsonwebtoken');

app.use(bodyParser.json()); // only parses json data
app.use(bodyParser.urlencoded({ // handles the urlencoded bodies
    extended: true
}));

const myJWTSecretKey = 'my-secret-key'; // set secret key, which we will use for creating and decoding JWT tokens, keep it safe.

app.get('/', (req, res) => {
    // get user object from the data source, Ex: database 
    const user = {
        email: '[email protected]',
        id: 1,
        name: 'Arjun A'
    };
    // sign with default (HMAC SHA256) 
    const token = jsonWebToken.sign(user, myJWTSecretKey);
    res.json({
        token: token
    });
});

// GET - http://localhost:3000/verify/{token}
app.get('/verify/:token', (req, res) => {
    try {
        const tokenDecodedData = jsonWebToken.verify(req.params.token, myJWTSecretKey);
        return res.json({
            error: false,
            data: tokenDecodedData
        });
    } catch (error) {
        res.json({
            error: true,
            data: error
        });
    }
})

app.listen(3000, () => {
    console.log(`Server is running at: 3000`);
});

Start server and test it

Issue following command from the root of your project $ node server.js, and point your browser to http://localhost:3000.

If everything goes well you should able to see bellow output:

{"token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6ImFyanVucGhwQGdtYWlsLmNvbSIsImlkIjoxLCJuYW1lIjoiQXJqdW4gQSIsImlhdCI6MTQ5OTM2NjM0NH0.xRJo4je_4QIyqJpyes8ixxekTqI2EQ6v8_zW3YuG_tE"}

You can verify and decode above token, by pointing your browser with token, http://localhost:3000/verify/eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6ImFyanVucGhwQGdtYWlsLmNvbSIsImlkIjoxLCJuYW1lIjoiQXJqdW4gQSIsImlhdCI6MTQ5OTM2NjM0NH0.xRJo4je_4QIyqJpyes8ixxekTqI2EQ6v8_zW3YuG_tE

If everything goes well you should able to see bellow output:

{"error":false,"data":{"email":"[email protected]","id":1,"name":"Arjun A","iat":1499366344}}
0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments