jwt library nodejs code example

Example 1: jwt in node js

// index.js 

const express = require('express');
const jwt = require('jsonwebtoken');

const app = express();

// generate token for another API to use in req.header
app.post('/login', (req, res) => {
    const user = {
        id: 1,
        username: 'abhishek',
        email: "[email protected]"
    }
    let token = jwt.sign({ user: user }, 'shhhhh');
    res.send(token);
})

// verifyToken is a function that is used for check in API that token exist or not
// it can be put in between n number of API to check that authoriZed user loggedin or not.
app.get('/api', verifyToken, (req, res) => {
    try {
        jwt.verify(req.token, 'shhhhh', (error, authData) => {
            if (error) {
                res.send("not logged in")
            }
            res.json({
                message: "post Created",
                authData
            })
        })
    } catch (error) {
        res.send(error)
    }
})

// This funtion is middleware. 
function verifyToken(req, res, next) {
    try {
        const bearerHeader = req.headers['authorization'];
        if (typeof bearerHeader !== 'undefined') {
            const bearerToken = bearerHeader.split(' ')[1];
            req.token = bearerToken;
            next();
        }
        else {
            res.send("Not logged-in")
        }
    }
    catch {
        res.send("something went wrong")
    }
}

app.listen(3000, () => {
    console.log("server is runing")
})

Example 2: jwt implementation in node js

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 })
	res.end()
}