JsonWebToken with express in node

Ricardo Arbois Jr.
2 min readSep 13, 2021

JSON Web Tokens are an open, industry standard RFC 7519 method for representing claims securely between two parties.

JWT.IO allows you to decode, verify and generate JWT.

Source: https://jwt.io/

npm i express jsonwebtoken --save

“dependencies”: {

“express”: “⁴.17.1”,

“jsonwebtoken”: “⁸.5.1”

}

In this section we assign our following package

const express = require(“express”)

const JWT = require(‘jsonwebtoken’)

Then assign express to passed express.json and express.unlencoded for incoming request.

const app = express()

app.use(express.json({}))

app.use(express.urlencoded({ extended:true}))

In this section we assign a middleware to verify the token.

const verifyToken = async(req,res,next) =>{

const bearerHeader = req.headers[“authorization”]

if(bearerHeader){

const bearer = bearerHeader.split(“ “)[1] req.token = bearer; next();

}

else{

return res.json({ msg: “Forbidden request.” })

}

}

This section we receive the request using a dummy account and return a json token once confirm.

app.post(“/login”, (req,res)=>{

const userData ={

fullname: “Ricardo Arbois”, username: “ricky”, password: 12345 }

const { username, password } = req.body

if( username == userData.username && password == userData.password){

delete userData.password

JWT.sign({userData},”secretKey”,{expiresIn: “30s”},

(err, token) =>{

res.json({token})

}

)}

else{

return res.status(401).json({

error: true,

message: “Username or Password is invalid”

})

}

})

Using the middleware we create a while ago, this will verify the incoming request .

app.post(“/welcome”, verifyToken,(req, res)=>{

JWT.verify(req.token,”secretKey”,

(err,authData)=>{

if(err){

return res.json({ msg: “Token Expires” })

}

else{

res.json({ msg: “Authentication successfully”, authData })

}

})

})

You can assign whether each page need to verify or assign a normal request just like below.

app.get(“/home”,(req,res)=>{

res.json({ msg: “Welcome to Home Page” })

})

Finally we assign port 5000 to run our JWT sample program.

const PORT = 5000

app.listen(PORT,()=>console.log(“Server running on port “+ PORT))

There are many way to secure your website and JsonWeb Token was one of them. Feel free to try. If you want more please leave a comment.

Youtube tutorial: https://www.youtube.com/watch?v=8xQUPv_6CsE

Thank you!

--

--

Ricardo Arbois Jr.

Fullstack Developer, AI , System Developer,System Engineer, Living a simple life and love too code.