How can I implement user authentication with JWT in an Express js app

0 votes
With the help of proper code and its explanation, can you explain how I can implement user authentication with JWT in an Express.js app?
Dec 17, 2024 in Java-Script by Ashutosh
• 14,020 points
57 views

1 answer to this question.

0 votes

In an Express.js application, you can use JWT (JSON Web Token) to implement user authentication by doing the following:

1. Install Required Packages

You'll need express, jsonwebtoken, bcryptjs (for password hashing), and dotenv for environment variables.

npm install express jsonwebtoken bcryptjs dotenv

2. Set Up Environment Variables

Create a .env file to store your secret key and other sensitive details:

JWT_SECRET=your-secret-key

JWT_EXPIRATION=1h

3. Code Example

Here's how you can implement user authentication:

// Load environment variables

require('dotenv').config();

const express = require('express');

const jwt = require('jsonwebtoken');

const bcrypt = require('bcryptjs');

const dotenv = require('dotenv');

// Initialize Express app

const app = express();

app.use(express.json()); // For parsing JSON requests


// Mock User Data (For demonstration, you should use a database)

const users = [

    { id: 1, username: 'Sita', password: '$2a$10$Qc7HvZfFHKIjs98MNQ6Fe6bNXUpEJd3oU5Rj0YdiO0zSM0X.5NK7G' } // Password: 'hellothere123'

];

// Login Route

app.post('/login', async (req, res) => {

    const { username, password } = req.body;

    // Find user by username

    const user = users.find(u => u.username === username);

    if (!user) {

        return res.status(400).send('User not found');

    }

    // Compare password

    const isMatch = await bcrypt.compare(password, user.password);

    if (!isMatch) {

        return res.status(400).send('Invalid password');

    }

    // Create JWT

    const token = jwt.sign(

        { id: user.id, username: user.username },

        process.env.JWT_SECRET,

        { expiresIn: process.env.JWT_EXPIRATION }

    );

    

    // Send token

    res.json({ token });

});

// Middleware to verify JWT

const authenticate = (req, res, next) => {

    const token = req.header('Authorization')?.replace('Bearer ', '');

    if (!token) {

        return res.status(403).send('Access denied');

    }

    try {

        const decoded = jwt.verify(token, process.env.JWT_SECRET);

        req.user = decoded;

        next();

    } catch (error) {

        res.status(400).send('Invalid token');

    }

};

// Protected Route Example

app.get('/protected', authenticate, (req, res) => {

    res.send(`Hi, ${req.user.username}`);

});

// Start the server

const PORT = process.env.PORT || 5000;

app.listen(PORT, () => {

    console.log(`Server is running on port ${PORT}`);

});

answered Dec 17, 2024 by Navya

Related Questions In Java-Script

0 votes
1 answer

How can we create an HTTPS server in Node.js?

Hii, The Express API doc spells this out pretty clearly. I ...READ MORE

answered Apr 24, 2020 in Java-Script by Niroj
• 82,840 points
875 views
0 votes
1 answer

How do I select an element with its name attribute in jQuery?

Hello @kartik, You can use: jQuery('[name="' + nameAttributeValue + ...READ MORE

answered Jun 11, 2020 in Java-Script by Niroj
• 82,840 points
1,103 views
0 votes
2 answers

How can I set focus on an element in an HTML form using JavaScript?

Hi Kartik, try the following script <script>  (window.onload = ...READ MORE

answered Sep 24, 2020 in Java-Script by Okugbe
• 280 points
1,905 views
0 votes
1 answer

How can I check the existence of an element in jQuery?

Hello @ Arpit In JavaScript, everything is 'truthy' or ...READ MORE

answered Sep 8, 2020 in Java-Script by Niroj
• 82,840 points
926 views
0 votes
1 answer

How do you implement API request validation in Express using middleware?

1. Create Middleware Function :  - Define a ...READ MORE

answered Oct 25, 2024 in Web Development by kavya
173 views
0 votes
1 answer
0 votes
0 answers

How do I create a custom theme in react?

With the help of coding examples, can ...READ MORE

Dec 19, 2024 in Web Development by Ashutosh
• 14,020 points
41 views
0 votes
1 answer
0 votes
1 answer

How can I use jQuery to select all elements with multiple CSS classes?

You can use the following syntax to ...READ MORE

answered Dec 17, 2024 in Java-Script by Navya
42 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP