DEV Community

Cover image for Secure our website using JWT (JSON Web Token) in nodeJS or expressJS
Deepak Jaiswal
Deepak Jaiswal

Posted on • Edited on

3 1 1 1 1

Secure our website using JWT (JSON Web Token) in nodeJS or expressJS

here we are using JWT to secure our application or website from unauthenticated user they try to access our data.

In npmjs a library named is

jsonwebtoken

npm i jsonwebtoken

if we only check user isAuthenticated or not we simply pass the middleware in between request and response

auth.js

`export default function getTokenFromUser(req: Request) {
  const authorization = req.headers.token;
  var decoded = jwt.verify(authorization, 'secret');
  if (!decoded) {
    throw new TokenError("No Authorization Header");
  }
  try {
    const token = decoded?.split("User data ")[1];
    return token;
  } catch {
    throw new TokenError("Invalid Token Format");
  }
}`
Enter fullscreen mode Exit fullscreen mode

we simple pass this auth of in between req,res

app.post('/api/post',auth,(req,res)=>{
//if some operation on code we use middleware
const token=jwt.sign({
  data: 'your data to store as token'
}, 'secret', { expiresIn: '1h' });

res.header('token',token).send("success")
});
Enter fullscreen mode Exit fullscreen mode

we ensure that you can save your secret key in your config file.

Do your career a big favor. Join DEV. (The website you're on right now)

It takes one minute, it's free, and is worth it for your career.

Get started

Community matters

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

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay