In Express.js, you can implement middleware to check if a user is authenticated before allowing them to access certain routes or resources. Here's a basic example of how you can create such middleware:
javascript// authMiddleware.js
const authMiddleware = (req, res, next) => {
// Check if user is authenticated
if (req.isAuthenticated()) {
// If authenticated, move to the next middleware or route handler
return next();
}
// If not authenticated, redirect to login page or send an error response
res.status(401).json({ message: 'Unauthorized' });
};
module.exports = authMiddleware;
In this example, the middleware checks if the user is authenticated using req.isAuthenticated()
. The next()
function is called if the user is authenticated, allowing the request to proceed to the next middleware or route handler. If the user is not authenticated, a 401 Unauthorized status is sent as a JSON response.
Now, you can use this middleware in your Express application as follows:
javascript// app.js
const express = require('express');
const session = require('express-session');
const passport = require('passport');
const authMiddleware = require('./authMiddleware');
const app = express();
// Set up session and passport middleware (assuming you're using passport for authentication)
app.use(session({ secret: 'your-secret-key', resave: true, saveUninitialized: true }));
app.use(passport.initialize());
app.use(passport.session());
// Your authentication strategies and routes setup with passport go here...
// Use the authMiddleware for routes that require authentication
app.get('/authenticated-route', authMiddleware, (req, res) => {
res.json({ message: 'You are authenticated!' });
});
// Start the server
const port = 3000;
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});
Make sure to replace the placeholder values with your actual secret key and set up passport with your preferred authentication strategy (local, OAuth, etc.).
This is a basic example, and depending on your specific authentication setup, you may need to adjust the middleware accordingly.