Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

236
Vistas
How to use different session for different routes in express?

I am trying to make the login/logout functionality of two category, admin & employee.
And When used app.use(session()) session will be available to every routes. And that is great. But when I want to logout lets say admin using req.session.destroy(). It logs out but the entire session is gone including admin as well as the employee. And that's not i want. I want to destroy only admin related session for admin logout and employee related session for employee logout. So, how can I do this?
And I am new to authentication and authorization. Do let me know what's the best practices using sessions, or is it better to JWT or anything which will help me be better at it.
For this related question.
my app.js


// session
app.use(
  session({
    secret: process.env.SECRET,
    resave: false,
    saveUninitialized: false,
    store,
    cookie: {
      maxAge: 20000,
      secure: false,
    },
  })
);

app.use("/api/admin", adminRoutes);
app.use("/api/employee", employeeRoutes);

app.get("/api", (req, res) => {
  res.send("Api is running");
});

and when the api/admin/login route is called this controller is called,

const adminLoginController = asyncHandler(async (req, res) => {
  console.log("I ran");
  const { pass } = req.body;

  if (someDBCheckHere) {
    req.session.adminAuthenticated = true;
    req.session.admin = { pass: pass };
    res.send("success");
  } else {
    res.status(401).send({ message: "Login Failed" });
    console.log("failure");
  }
});

over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

I'm not really sure why you would destroy the session. Did you read it somewhere that tell you to do so?
So from the behavior, you can see the session is intended to live, not to be destroy :D

To "logout" a user, you just set set the cookie to an expire date

over 4 years ago · Santiago Trujillo Denunciar

0

Please confirm whether my interpretation of your requirement is correct:

Your users can log on in two roles, with different passwords per role. And they might even be logged on in both roles simultaneously (either by giving two passwords, or because the admin role includes the employee role).

You could achieve this by having only one session, with attributes req.session.employeeAuthenticated and req.session.adminAuthenticated. After validating a password, you would set one (or both) of these attributes, and users could also "log out from the admin role", after which you would simply set req.session.adminAuthenticated = false but keep the session.

The first of the adminRoutes must then validate that the current user indeed has the admin role:

function(req, res, next) {
  if (req.session.adminAuthenticated) next();
  else res.status(403).end("Forbidden for non-admins");
}

(and likewise in employeeRoutes).

Only when the user logs out completely would you call req.session.destroy().

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda