jwt express node js 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: express jwt

// JWT MIDDLEWARE
const jwt = require('jsonwebtoken')
const httpError = require('http-errors')

module.exports = (req, res, next) => {
  try {
    const tokenHeader = req.headers.authorization.split('Bearer ')[1]
    const decoded = jwt.verify(tokenHeader, process.env.ACCESS_TOKEN_SECRET)
    req.user = decoded
    next()
  } catch (err) {
    next(httpError(401))
  }
}

// ROUTE LOGIN
app.get('/protect', authJwt, (req, res) => {
  console.log(req.user)
  res.send('aim in proteced route')
})

app.post('/login', (req, res) => {
  const bodyPayload = {
    id: Date.now(),
    username: req.body.username
  }
  const token = signAccessToken(res, bodyPayload)
  return res.status(200).json(token)
})

app.post('/refresh-token', (req, res) => {
  const refreshToken = signRefreshToken(req)
  res.status(200).json(refreshToken)
  res.end()
})

// JWT HELPER
const jwt = require('jsonwebtoken')
const httpError = require('http-errors')

exports.signAccessToken = (res, payload) => {
  try {
    if (payload) {
      const accessToken = jwt.sign({ ...payload }, process.env.ACCESS_TOKEN_SECRET, { expiresIn: '1m' })
      const refreshToken = jwt.sign({ ...payload }, process.env.REFRESH_TOKEN_SECRET, { expiresIn: '90d' })
      res.cookie('refreshToken', `${refreshToken}`, { expired: 86400 * 90 })
      return { accessToken, refreshToken }
    }
  } catch (err) {
    return httpError(500, err)
  }
}

exports.signRefreshToken = (req) => {
  try {
    const getToken = req.cookies.refreshToken
    if (getToken) {
      const { id, username } = jwt.verify(getToken, process.env.REFRESH_TOKEN_SECRET)
      const accesssToken = jwt.sign({ id, username }, process.env.ACCESS_TOKEN_SECRET, { expiresIn: '1m' })
      return { accesssToken }
    }
  } catch (err) {
    return httpError(401, err)
  }
}

Tags:

Misc Example