How to use JWT instead of sessions in Node js


Let’s use JWT instead of session in Node js for making web apps. Ok firstly we should install all package for our app. We need express.js and auth-verify

  • express.js for handling with web app
  • auth-verify for making JWT and verifying it

So, we should make our project file and install necessary libraries

mkdir jwt-app && cd jwt-app
Enter fullscreen mode

Exit fullscreen mode

npm install express auth-verify
Enter fullscreen mode

Exit fullscreen mode

Ok, now we should create our index.js file:

const express = require('express');
const AuthVerify = require('auth-verify');

const app = express();
const auth = new AuthVerify({jwtSecret: 'supersecret', storeTokens: 'memory'}); // if you have redis you can save your tokens in redis
Enter fullscreen mode

Exit fullscreen mode

Now we will make JWT token when user/client visits to our web app.

app.get('/', async (req, res)=>{
    const payload = {id:1, role: 'user'} // it's payload of JWT
    await auth.jwt.sign(payload, '10m', { res }); // '10m' means expiry time of jwt 
    res.send('JWT saved');
});

app.listen(3000, ()=>{
    console.log('Server listening!'); // Our app is running on localhost:3000
});
Enter fullscreen mode

Exit fullscreen mode

With auth-verify we can save it automatically without any manual steps. For automatically saving you should use { res }. {res} means that when client sends request to server. Server reply with response and auth-verify can get JWT token from this request.
Now check our web app:

Result

And for verifiying the user/client we will create localhost:3000/verify page. So it should be like this:

app.get("/verify", async (req, res) => {
  try {
    const data = await auth.jwt.verify(req); // auto reads from cookie
    res.json({ valid: true, data });
  } catch (err) {
    res.json({ valid: false, error: err.message });
  }
});
Enter fullscreen mode

Exit fullscreen mode

And with req auth-verify can get JWT token from client request and can verify it. And ifJWT token verified the result should be like this:

Result

So everything is working!🥹
Full code of our web app:

const express = require('express');
const AuthVerify = require('auth-verify');

const app = express();
const auth = new AuthVerify({jwtSecret: 'supersecret', storeTokens: 'memory'});

app.get('/', async (req, res)=>{
    const payload = {id:1, role: 'user'}
    await auth.jwt.sign(payload, '10m', {res});
    res.send('JWT saved');
});

app.get("/verify", async (req, res) => {
  try {
    const data = await auth.jwt.verify(req); // auto reads from cookie
    res.json({ valid: true, data });
  } catch (err) {
    res.json({ valid: false, error: err.message });
  }
});

app.listen(3000, ()=>{
    console.log('Server listening!');
});
Enter fullscreen mode

Exit fullscreen mode

So we can conclude our article with that the main difference between JWT token and sessions while session are saved to server, JWT tokens are saved to clients!



Source link

Leave a Reply

Your email address will not be published. Required fields are marked *