Authentication middleware in a Node.js and Express

Authentication middleware in a Node.js and Express

ยท

3 min read

Certainly! Creating an authentication middleware in a Node.js and Express application involves setting up middleware to verify whether a user is authenticated before allowing access to certain routes. Below is a step-by-step guide to create a basic authentication middleware.

Step 1: Set Up Your Project

  1. Create a new project folder:

     mkdir authentication-middleware
     cd authentication-middleware
    
  2. Initialize a new Node.js project:

     npm init -y
     npm install express
    

Step 2: Create Your Folder Structure

Create the following folder structure:

authentication-middleware/
|-- src/
|   |-- middleware/
|       |-- authenticate.js
|   |-- routes/
|       |-- publicRoutes.js
|       |-- protectedRoutes.js
|   |-- app.js
|-- server.js

Step 3: Set Up Express Server

In app.js, set up an Express server and use the authentication middleware:

const express = require('express');
const publicRoutes = require('./routes/publicRoutes');
const protectedRoutes = require('./routes/protectedRoutes');
const authenticateMiddleware = require('./middleware/authenticate');

const app = express();

// Public routes (no authentication required)
app.use('/public', publicRoutes);

// Middleware to authenticate
app.use(authenticateMiddleware);

// Protected routes (authentication required)
app.use('/protected', protectedRoutes);

module.exports = app;

Step 4: Create Public Routes

In routes/publicRoutes.js, set up routes that don't require authentication:

const express = require('express');
const router = express.Router();

router.get('/welcome', (req, res) => {
  res.send('Welcome to the public route!');
});

module.exports = router;

Step 5: Create Protected Routes

In routes/protectedRoutes.js, set up routes that require authentication:

const express = require('express');
const router = express.Router();

router.get('/dashboard', (req, res) => {
  res.send('Welcome to the protected route. You are authenticated!');
});

module.exports = router;

Step 6: Create Authentication Middleware

In middleware/authenticate.js, create the authentication middleware:

const authenticateMiddleware = (req, res, next) => {
  // Check if the user is authenticated (you can customize this based on your authentication mechanism)
  const isAuthenticated = true; // Replace with your actual authentication check

  if (isAuthenticated) {
    // User is authenticated, proceed to the next middleware or route handler
    next();
  } else {
    // User is not authenticated, send unauthorized response
    res.status(401).send('Unauthorized. Please log in.');
  }
};

module.exports = authenticateMiddleware;

Step 7: Run Your Application

In server.js, use the exported app to start the application:

const app = require('./src/app');

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

app.listen(PORT, () => {
  console.log(`Server is running on http://localhost:${PORT}`);
});

Start the server:

node server.js

Step 8: Test Public and Protected Routes

  1. Public Route:

    Open your browser and navigate to http://localhost:3000/public/welcome. You should see the message "Welcome to the public route!".

  2. Protected Route:

    Open your browser and navigate to http://localhost:3000/protected/dashboard. Since there is no actual authentication logic in the example, you'll see the message "Welcome to the protected route. You are authenticated!". In a real application, you would implement a proper authentication mechanism.

Congratulations! You've created a basic authentication middleware to protect certain routes in your Node.js and Express application. Customize the authentication logic in the middleware based on your specific requirements and integrate it with a proper user authentication system.

Did you find this article valuable?

Support Revive Coding by becoming a sponsor. Any amount is appreciated!

ย