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.

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

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

Okay