Quick Guide: Building an API Server with Express and JWT Authentication

In this tutorial, I'll walk you through setting up a simple API server using Express and express-jwt for JSON Web Token (JWT) authentication. By the end, you'll have a functional server that can issue JWTs and verify them for secure endpoints. Let's dive in!

Step 1: Setup and Install Dependencies

First, create a new project directory and initialize a Node.js project. Then, install the required packages:

mkdir express-jwt-api
cd express-jwt-api
npm init -y
npm install express express-jwt jsonwebtoken body-parser

Step 2: Create the Basic Server

Create a server.js file to set up your Express server:

const express = require('express');
const bodyParser = require('body-parser');
const routes = require('./routes');

const app = express();
app.use(bodyParser.json());
app.use('/api', routes);

const PORT = 3000;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));

This code sets up an Express server and uses body-parser to parse JSON requests.

Step 3: Define Routes

Create a routes.js file for defining our API routes. We'll add a login route to generate JWTs and a protected route that requires JWT verification.

const express = require('express');
const jwt = require('jsonwebtoken');
const { verifyToken } = require('./middleware');

const router = express.Router();

// Login route to generate JWT
router.post('/login', (req, res) => {
    const { username, password } = req.body;
    if (username === 'testuser' && password === 'testpassword') {
        const user = { id: 1, username: 'testuser' };
        const token = jwt.sign(user, 'your_secret_key', { expiresIn: '1h' });
        res.json({ token });
    } else {
        res.status(401).json({ message: 'Invalid credentials' });
    }
});

// Protected route
router.get('/protected', verifyToken, (req, res) => {
    console.log('req.user:', req.user);
    if (req.user && req.user.id) {
        res.json({ message: 'Protected route accessed.', userId: req.user.id });
    } else {
        res.status(401).json({ message: 'Unauthorized' });
    }
});

router.get('/public', (req, res) => res.send('This is a public route.'));

module.exports = router;

Step 4: Implement JWT Verification

Create a middleware.js file to define the JWT verification middleware:

const { expressjwt } = require('express-jwt');

const verifyToken = expressjwt({
    secret: 'your_secret_key',
    algorithms: ['HS256'],
    requestProperty: 'user'
});

module.exports = { verifyToken };

This middleware verifies the JWT and attaches the decoded payload to req.user.

Step 5: Test Your API

  1. Start the server:

    node server.js
    
  2. Generate a JWT by sending a POST request to /api/login with a JSON body { "username": "testuser", "password": "testpassword" }. You'll get a token in response.

  3. Use the token to access the protected route:

    curl -H "Authorization: Bearer YOUR_JWT" http://localhost:3000/api/protected
    

    You should see a response with the user ID from the token.

Conclusion

You've now set up a basic API server with Express and JWT authentication! This setup allows you to issue and verify JWTs, providing a foundation for secure API endpoints. Feel free to expand on this by integrating a database for user management or adding more endpoints.


Feel free to modify and expand this guide to suit your needs. Happy coding! 🧑‍💻🚀

Comments

  1. Markdown is allowed. HTML tags allowed: <strong>, <em>, <blockquote>, <code>, <pre>, <a>.