Home > database >  how to add a session request for all routes nodejs
how to add a session request for all routes nodejs

Time:09-15

How to set verification of session for all routes?

if(req.session.lang) req.session.lang 
else req.session.lang = "pt";
const tradutor = require('../scripts/lang/lang-' req.session.lang '');
var traduPT = new tradutor();

this is my code. i want use for check in all routes, maybe something like adding the code and just applying the request on the routes, but how and where to do this code outside the routes?

CodePudding user response:

You can create route-specific middleware.

// validate.js

export const validateSession = (req, res, next) => {
    // if the user is logged in, continue
    if (req.session.isLoggedIn) return next();
    // otherwise, don't continue and go back to the /home route
    res.redirect('/home');
};

Then pass it in as the second argument when defining your route:

// main.js
import { validateSession } from './validate.js';

app.get('/dashboard', validateSession, (req, res) => { /* ... */ });

app.get('/login', validateSession, (req, res) => { /* ... */ });

app.get('/foo', validateSession, (req, res) => { /* ... */ });
  • Related