Jwt node js: What is it and How to implement it based authentication


Jwt node js is a means of representing claims that are transferred between 2 parties. In other words, it creates access tokens for an app. A high quality JWT implementation will benefit both developers and app users. How?

Today, ArrowHiTech‘s committed team will deliver an article on jwt node jsto you. All these questions will be answered in no time:

  1. What is jwt node js?
  2. When to use it?
  3. Is it really important?
  4. How to implement jwt node js?

Alright, without further ado, let’s get started!

What is Jwt node js?

Jwt node js stands for JSON Web Token. What’s more, it is an open Internet standard used for creating and transmitting data as a JSON object. Because it is signed digitally, the data is safely secured and verified.

(JWT uses HMAC algorithm or public/private key pairs like RSA or ECDSA. Plus, the signature will certify that the one that signed is only the party having the private key.)

jwt token

Now let’s look at JWT Structure to understand it further!

Jwt node js Structure

There are 3 parts in JWT: header, payload and signature. They are separated by dots (.). As a result, a JSON web token looks like this



Header is made up of 2 main parts:

  • signing algorithm: HMAC, RSA or SHA256
  • token type: jwt node js

For example:

  "alg": "HMAC",
  "typ": "JWT"


Payload in jwt node js is used to contain claims. To clarify, claims are statement that show entity (user) and extra data. In payload, there are 3 types of claims you need to know:

  • Registered: not required but highly recommended. These claims are effective and inter-operable. For example:
    • iss (issuer),
    • sub (subject),
    • exp(expiration time),
    • aud(audience)
  • Public: is defined up to developers. However, we highly suggest choosing IANA jwt node js Registry or defining them as URI with collision resistant abilities so as to avoid collisions.
  • Private: are custom claims. Private claims can share data among parties and in now way be the same as registered and public claims.

Let’s have a look at this Payload example:

  "sub": "0123456789",
  "name": "ArrowHiTech",
  "admin": true


Firstly, take the encoded header and payload. Then sign the algorithm specified in the header (HMAC in the above example).

  base64UrlEncode(header) + "." +

Signature helps verify that the message stays the same throughout the process. Moreover, if it’s signed with a private key, Signature verifies the jwt node js sender.

jwt structure

When to use jwt node js?

There are 2 ideal situations where you should use jwt node js:

  1. Authorization: (most common situation). After user logging in, all the following requests will have jwt node js to let them access routes, services and resources.
  2. Info Exchange: will securely transmit data among parties.

Is it necessary?

The answer is YES. Here, we will illustrate some benefits of JSON Web Token over other types (SWT or SAML):

  • Small size, more compact: easy to pass in HTML and HTTP
  • Securely signed: and even more simple to do it
  • JSON parsers: can map to objects directly, which is common in most programming languages.
  • Internet scale: available on different platforms: webs, desktops, and mostly mobile.

Now that you’ve seen the importance of JWT. Yet, how to implement it in Node.js? Let’s find out!

How to implement Jwt node js?

There are 5 simple steps you need to know. Now, it’s time to slowly but surely discover them!

HTTP Server

First thing first: creating a HTTP server. Use the index.js like follows:

const express = require("express")
const bodyParser = require("body-parser")
const cookieParser = require("cookie-parser")

const { signIn, welcome, refresh } = require("./handlers")

const app = express()

app.post("/signin", signIn)
app.get("/welcome", welcome)
app.post("/refresh", refresh)


Then, define signIn and welcome routes.

User’s Sign In

signIn routes will take user’s credentials and sign those in. To clarify, it could be password or bank number, etc. Next, write the signIn HTTP hander in another file hander.js. Here is an example for 2 valid users:

const jwt = require("jsonwebtoken")

const jwtKey = "my_secret_key"
const jwtExpirySeconds = 300

const users = {
	user1: "password1",
	user2: "password2",

const signIn = (req, res) => {
	// Get credentials from JSON body
	const { username, password } = req.body
	if (!username || !password || users[username] !== password) {
		// return 401 error is username or password doesn't exist, or if password does
		// not match the password in our records
		return res.status(401).end()

	// Create a new token with the username in the payload
	// and which expires 300 seconds after issue
	const token = jwt.sign({ username }, jwtKey, {
		algorithm: "HS256",
		expiresIn: jwtExpirySeconds,
	console.log("token:", token)

	// set the cookie as the token string, with a similar max age as the token
	// here, the max age is in milliseconds, so we multiply by 1000
	res.cookie("token", token, { maxAge: jwtExpirySeconds * 1000 })

Overall, the process will automatically produce cookies when user logs in with correct credentials.

jwt signin

Post Authentication Routes

The next step is to handle post authentication routes. The goal is to:

  • authenticate following requests from users.
  • get info about those users

For this step, you need to use welcome handler in the above file we just made:

const welcome = (req, res) => {
	// We can obtain the session token from the requests cookies, which come with every request
	const token = req.cookies.token

	// if the cookie is not set, return an unauthorized error
	if (!token) {
		return res.status(401).end()

	var payload
	try {
		// Parse the JWT string and store the result in `payload`.
		// Note that we are passing the key in this method as well. This method will throw an error
		// if the token is invalid (if it has expired according to the expiry time we set on sign in),
		// or if the signature does not match
		payload = jwt.verify(token, jwtKey)
	} catch (e) {
		if (e instanceof jwt.JsonWebTokenError) {
			// if the error thrown is because the JWT is unauthorized, return a 401 error
			return res.status(401).end()
		// otherwise, return a bad request error
		return res.status(400).end()

	// Finally, return the welcome message to the user, along with their
	// username given in the token
	res.send(`Welcome ${payload.username}!`)

Token Renewal

We have made the examples to set for 5 minutes expiry time. However, you cannot expect users to sign in every 5 minutes, right? It’s time to renew tokens by creating another refresh route to renew expiry time.

const refresh = (req, res) => {
	// (BEGIN) The code uptil this point is the same as the first part of the `welcome` route
	const token = req.cookies.token

	if (!token) {
		return res.status(401).end()

	var payload
	try {
		payload = jwt.verify(token, jwtKey)
	} catch (e) {
		if (e instanceof jwt.JsonWebTokenError) {
			return res.status(401).end()
		return res.status(400).end()
	// (END) The code uptil this point is the same as the first part of the `welcome` route

	// We ensure that a new token is not issued until enough time has elapsed
	// In this case, a new token will only be issued if the old token is within
	// 30 seconds of expiry. Otherwise, return a bad request status
	const nowUnixSeconds = Math.round(Number(new Date()) / 1000)
	if (payload.exp - nowUnixSeconds > 30) {
		return res.status(400).end()

	// Now, create a new token for the current user, with a renewed expiration time
	const newToken = jwt.sign({ username: payload.username }, jwtKey, {
		algorithm: "HS256",
		expiresIn: jwtExpirySeconds,

	// Set the new token as the users `token` cookie
	res.cookie("token", newToken, { maxAge: jwtExpirySeconds * 1000 })

Lastly, export handlers at the end:

module.exports = {

Test the app – jwt node js

Firstly, to run the app, following this command

node ./index

Next, use HTTP client with cookie support and make one sign in request (with credentials)

POST http://localhost:8000/signin


Then, hit the welcome route to get the welcome message. And finally, hit refresh route to see new token cookie value

GET http://localhost:8000/welcome
POST http://localhost:8000/refresh

That’s all you need to know? Still finding it hard to understand?

Trouble implementing jwt node js? We are only one call away!

If you still have trouble implementing jwt node js, why not hiring experts? It is a very wise investment, which leads to time saving, cost effectiveness and outstanding results. ArrowHiTech is proud to be one of the leading IT Outsourcing agencies in Vietnam.

With over 14 years in the industries, satisfying more than 10,000 clients globally, we are confident that your issues will be solved in no time! Our services and solutions are fast, low cost and always bring a smile to all clients’ face! You can check out our portfolio as well as our Node JS Development Services for more details!

Final Words

Today, we have delivered an article on jwt node js – JSON Web Token and how to implement it in Node.js. ArrowHiTech hopes that you find it helpful for your journey!

And as always, we truly wish the best of luck and success will come to you! WE’D LOVE TO HEAR FROM YOU AT: