Authentication in Nodejs using JSON web tokens (JWT)

Search for a command to run...

No comments yet. Be the first to comment.
Twitter is one of the most popular social media platforms in the world, with over 330 million active users as of 2021. If you are interested in building a Twitter-like application, this tutorial will guide you through the process of building a FullSt...

Hey everyone, In this article, we will build our own Tic Tac Toe game using pure Javascript. https://youtu.be/lKe57l8sttw Code <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE...

Hi everyone, In this blog, we will learn how we can create node.js functions locally and deploy them to AWS Lambda using serverless. So, let's get started. Step 1. Create an AWS Account ☁️ In order to deploy functions to AWS Lambda, you should have a...

Hey there, In this article, we are going to learn how you can upload any file to firebase storage. Uploading files to firebase storage is really easy. I would I recommend you to code along with me for better understanding. So, let's get started. Step...

Hey there, Welcome back. In this article, I would be showing you how I made a collaborative IDE with a video call. The main application of this application is that you can create a room and people can join the room. You have the ability to write mark...

Hey there, In this article, we would be learning how to implement authentication in nodejs using express and JWT aka JSON web tokens
JSON web tokens or JWT is a simple long string that contains some data in an encoded way. Sounds confusing? here is an example
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiUGl5dXNoIEdhcmciLCJlbWFpbCI6ImluZm9AcGl5dXNoZ2FyZy5kZXYiLCJpYXQiOjE1MTYyMzkwMjJ9.XaQC6iMAgESX8b-HT2AkclCAWDnAmNiHV7tq7b6GWRE
You can decode the string by visiting https://jwt.io/ and paste the above string into the debugger present on the mentioned link.
{
"name": "Piyush Garg",
"email": "info@piyushgarg.dev",
"iat": 1516239022
}
I'll be guiding you step by step and I would highly recommend you to code along with me.
const express = require('express');
const cookieParser = require('cookie-parser')
const app = express();
app.use(express.json())
app.use(cookieParser())
app.get('/', (req, res) => {
res.send('Welcome to my API')
})
app.get('/profile', (req, res) => {
res.send('Hello')
})
app.listen(9000, () => console.log('Server Started at PORT 9000'))
A very basic express starter code. We would be protecting the ‘/profile’ route so that only logged in users can access that route.
For this project, we would be installing a few dependencies.
Express
jsonwebtoken
cookie-parser
npm install express jsonwebtoken cookie-parser
In this step, we would be creating functions which would be used as middlewares to protect our certain routes.

generateToken(): This function would take data as a parameter and return the token after generating it.
isLoggedIn(): This function is responsible for checking if the current user is logged in or not.
const jwt = require('jsonwebtoken');
function generateToken(payload) {
const token = jwt.sign(payload, 'mySecretKey');
return token;
}
function isLoggedIn(req, res, next) {
// Check if the user has token in cookies. If not return the request;
if(!req.cookies.jwt) return res.json({ error: 'Please Login' });
const clientToken = req.cookies.jwt;
try {
// Decode the client token by using same secret key that we used to sign the token
const decoded = jwt.verify(clientToken, 'mySecretKey');
req.user = decoded;
next();
}
catch(err){
return res.json({error: 'Invalid Token'})
}
}
module.exports = {
generateToken,
isLoggedIn
}
In auth.js we have created two functions as mentioned above. Please go through the code and you would understand the flow behind it.
Back to index.js let's create two routes signup route and login route.
In this article, I’ll be coding only the signup route.
Your assignment is to create the login route.
const express = require('express');
const cookieParser = require('cookie-parser')
const app = express();
// Import auth.js that we created earlier
const auth = require('./auth');
app.use(express.json())
app.use(cookieParser())
app.get('/', (req, res) => {
res.send('Welcome to my API')
})
app.get('/profile', (req, res) => {
res.send('Hello')
})
app.post('/signup', (req, res) => {
const {name, email, password} = req.body;
// .. code to save user in database
// Now lets generate token and give it to user as a cookie
const payload = {
name,
email
}
const token = auth.generateToken(payload);
res.cookie('jwt', token);
return res.redirect('/profile')
})
app.listen(9000, () => console.log('Server Started at PORT 9000'))
To protect your route, just call the isLoggedIn function as middleware before the route that you want to protect and that's it.
Updated profile route:
app.get('/profile', auth.isLoggedIn, (req, res) => {
res.send(`Hello ${req.user.name}`);
})
req.user holds the current user which is logged in. Navigate to auth.js line number 18:
req.user = decoded;
This is where we set the value of req.user to the current user.
Value of req.user is exactly the same as we defined the payload while generating the token.





Building REST API with Node.js Build your own REST API from scratchmedium.com Top 10 visual studio code extensions 2020 Best vscode extensions to make your development smooth and powerful.medium.com How to create a VS Code extension Hi there, in this article we would be creating an extension for VS Code and publishing it to the vscode marketplace.medium.com
Github: https://github.com/piyushgarg195
Linkedin: https://www.linkedin.com/in/piyushgarg195/
Website: https://www.piyushgarg.dev/