DEV Community

Developer Sabbir
Developer Sabbir

Posted on

How to create JWT accesstoken and refresh token & validate

dev-auth-middleware-jwt this package allows handle auth middleware.

This library will help us to generate access & refresh token also able to validate

INSTALLATION

$ npm i dev-auth-middleware-jwt --save
Enter fullscreen mode Exit fullscreen mode

or if you are use yarn then just run this code

$ yarn add dev-auth-middleware-jwt --save
Enter fullscreen mode Exit fullscreen mode

REQUIRED TASK

  • We have to create a .env file into the root project directory for store our all of environment variable.
  • Create all variable following the down below code example.
ACCESS_TOKEN_SECRET=key //use your secret key
ACCESS_TOKEN_EXPIRES_IN=1d //modify as you need eg: 60s, 1m, 1h, 7d

REFRESH_TOKEN_SECRET=key //use your secret key
REFRESH_TOKEN_EXPIRES_IN=1d //modify as you need eg: 60s, 1m, 1h, 7d
Enter fullscreen mode Exit fullscreen mode
  • That is required

USAGES

Firstly, just import this package using

import { JWT, Validate } from "dev-auth-middleware-jwt";
Enter fullscreen mode Exit fullscreen mode

Now it's ready to use.

If you want you try with this template. I just try to explement this package features and show...

import express, { Request, Response } from "express";
import dotenv from "dotenv";
import { JwtPayload } from "jsonwebtoken";
dotenv.config();
import { JWT, Validate } from "dev-auth-middleware-jwt";

declare module "express" {
  interface Request {
    user?: any;
  }
}

const app = express();
app.use(express.json());

let refreshTokens: any = [];
app.post("/", async (req: Request, res: Response) => {
  const { username, password } = req.body;
  try {
    const payload: JwtPayload = {
      id: "4234124123423535",
      username,
    };
    const accessToken = JWT.generateAccessToken(payload);
    const refreshToken = JWT.generateRefreshToken(payload);
    refreshTokens.push(refreshToken);

    // response
    res.status(200).json({
      data: {
        accessToken,
        refreshToken,
      },
    });
  } catch (error) {
    console.log(error);
    res.status(500).json({ message: "Something went wrong!", error });
  }
});

app.post("/pro", Validate.accessToken, async (req: Request, res: Response) => {
  if (req.user) {
    res.json({
      data: {
        user: req.user,
      },
    });
  } else {
    res.json({ data: { message: "User not found" } });
  }
});

app.post(
  "/get-ref",
  Validate.refreshToken,
  async (req: Request, res: Response) => {
    console.log(req.user);
    if (req.user) {
      res.json({
        data: {
          user: req.user,
        },
      });
    } else {
      res.json({ data: { message: "User not found" } });
    }
  }
);

const PORT = process.env.PORT || 4000;
app.listen(PORT, () => console.log(`🚀 Server is running at ${PORT}`));
Enter fullscreen mode Exit fullscreen mode

Author

This package created by Sabbir Hossain Shuvo. And the GitHub profile is https://github.com/devlopersabbir.

LICENSE

MIT

For support just Buy Me A Coffee
https://www.buymeacoffee.com/devlopersabbir

Image of Datadog

Master Mobile Monitoring for iOS Apps

Monitor your app’s health with real-time insights into crash-free rates, start times, and more. Optimize performance and prevent user churn by addressing critical issues like app hangs, and ANRs. Learn how to keep your iOS app running smoothly across all devices by downloading this eBook.

Get The eBook

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay