Explore our extensive collection of courses designed to help you master various subjects and skills. Whether you're a beginner or an advanced learner, there's something here for everyone.


Learn live

Join us for our free workshops, webinars, and other events to learn more about our programs and get started on your journey to becoming a developer.

Upcoming live events

Learning library

For all the self-taught geeks out there, here is our content library with most of the learning materials we have produced throughout the years.

It makes sense to start learning by reading and watching videos about fundamentals and how things work.

Search from all Lessons

LoginGet Started
← Back to Lessons
Edit on Github

Express JWT Authentication

1) Installation

1) Installation

Install these 3 libraries that will take care of generating the JWT tokens:

1npm install express-jwt @types/express-jwt jsonwebtoken @types/jsonwebtoken --save

2) Login endpoint

Second step is to create one API Route that can be called by the client to generate a token (a.k.a: login), this endpoint will receive the email and password information form the body and look for any user in the DB that matches those two values.

If the value is found, it will generate a token by calling the function jwt.sign.

1//this line goes in your public_routes.ts'/token', safe(createToken)); 3 4// this function goes in your actions.ts 5export const createToken = async (req: Request, res: Response): Promise<Response> =>{ 6 7 if(! throw new Exception("Please specify an email on your request body", 400) 8 if(!req.body.password) throw new Exception("Please specify a password on your request body", 400) 9 10 const userRepo = await getRepository(Users) 11 12 // We need to validate that a user with this email and password exists in the DB 13 const user = await userRepo.findOne({ where: { email:, password: req.body.password }}) 14 if(!user) throw new Exception("Invalid email or password", 401) 15 16 // this is the most important line in this function, it create a JWT token 17 const token = jwt.sign({ user }, process.env.JWT_KEY as string); 18 19 // return the user and the recently created token to the client 20 return res.json({ user, token }); 21}

3) Enforcement

Now we need to add a middleware that will check for the token on the Request Authoritzation Header. The middleware will intercept each request and execute the next function to proceed only if it succeeds in validating the token, otherwise it will return an error.

Add these two middlewares inside ./src/app.js that will take care of enforcing the token.

1// ⬆ anything ABOVE is public 2let opt: Options = { secret: process.env.JWT_KEY as string, algorithms: ["HS256"] } 3app.use(jwt(opt)) 4// ⬇ anything BELOW is public 5app.use(((err: any, req: any, res: any, next: any) => { 6 if (err) console.error(err); 7 if ( === 'UnauthorizedError') { 8 return res.status(401).json({ status: err.message }); 9 } 10 next(); 11}))

⚠️ Important

Any endpoint that is added BELOW these middlewares will be private, for example:

1app.get('/public', (req, res) => { 2 res.json({ message: "Anyone can see me" }); 3}) 4 5// ⬆ anything ABOVE is public 6app.use(jwt(opt)) // ⬅ JWT Middleware 7// ⬇ anything BELOW is public 8 9app.get('/private', (req, res) => { 10 res.json({ message: "If you can se me, you are logged in" }); 11})

3) Get the authenticated user

We are done, but if only logged in users are supposed to call our private endpoints, then we need a way to know who is calling them, for example we can use req.user from now on, to identify request user):

1export const getMe = async (req: Request, res: Response): Promise<Response> =>{ 2 3 const users = await getRepository(Users).find({ where: }); 4 // ⬇ not comming from the BD 5 return res.json(req.auth); 6}

Or we can use that info and get more information form the requester from the database.

1export const getMe = async (req: Request, res: Response): Promise<Response> =>{ 2 3 4 // ⬇ not comming from the BD 5 return res.json(req.auth); 6}