How to create a Session Based Authentication in Node.js

Session-based authentication module for a Node.js backend using the express-session library. This example assumes you have a user model and a database to store user information.

First, install the express-session library by running npm install express-session in your project directory.

				
					// Require the necessary modules
const session = require('express-session');

// Configure session middleware
const sessionMiddleware = session({
  secret: 'yourSecretKey', // Secret key used to sign the session ID cookie
  resave: false,
  saveUninitialized: false,
  cookie: {
    secure: true, // Enable secure cookies for HTTPS
    httpOnly: true, // Prevent client-side JavaScript access to cookies
    maxAge: 24 * 60 * 60 * 1000 // Cookie expiration time (1 day)
  }
});

// Generate a session and store user information
function generateSession(req, user) {
  req.session.userId = user.id;
  req.session.username = user.username;
  // You can store additional user information in the session as needed
}

// Middleware to check if a user is authenticated
function authenticate(req, res, next) {
  if (!req.session.userId) {
    // User is not authenticated, redirect or send an error response
    return res.status(401).json({ message: 'Not authenticated' });
  }

  // User is authenticated, proceed to the next middleware or route
  next();
}

module.exports = {
  sessionMiddleware,
  generateSession,
  authenticate,
};
				
			

To use this module, you need to add the sessionMiddleware to your Express app’s middleware stack and utilize the generateSession and authenticate functions as needed. Here’s an example of how you can use it:

				
					const express = require('express');
const auth = require('./auth'); // Assuming you've named the file 'auth.js'

const app = express();

// Add the session middleware to the Express app
app.use(auth.sessionMiddleware);

// Example route for login
app.post('/login', (req, res) => {
  // Authenticate the user
  const user = {
    id: 1,
    username: 'exampleuser',
    // Other user properties...
  };

  auth.generateSession(req, user);

  res.json({ message: 'Login successful' });
});

// Example protected route that requires authentication
app.get('/protected', auth.authenticate, (req, res) => {
  // Access the authenticated user's information from the session
  const userId = req.session.userId;
  const username = req.session.username;

  res.json({ message: 'You are authenticated!', userId, username });
});

// Start the server
app.listen(3000, () => {
  console.log('Server running on port 3000');
});
				
			

Please note that this is a basic example to help you get started. In a production environment, you would likely want to enhance the error handling, add proper user validation, integrate with a database, and possibly include additional security measures. Additionally, make sure to configure the cookie options according to your specific requirements, including appropriate secure settings based on your deployment environment.