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

108
Vistas
Express - Check if session exist

I am setting up my NodeJS & Express App, using Passport for authentication with Google Sign In and Login. Everything works very well when working on localhost.

The signin process works very well, and I can see the user information attached to req.user contains all user information.

However, right after that, when calling any route, req.user is undefined

I try desperately, to check if any session doesent exist to redirected that, on my login page, but it gives me some error based on Unexpected token

index.js:

const express = require("express");
const passport = require("passport");
const GoogleStrategy = require("passport-google-oauth20").Strategy;
const app = express()
const port = 5000

// if user is not logged-in redirect back to login page
app.use(function(req, res, next) {
   if (req.session.user == null){
   res.redirect('http://localhost:3000/login');
   }   else {
    next();
   }
});

app.use(
  session({
  secret: 'keyboard cat',
  resave: false,
  cookie: { httpOnly: false, secure: false, maxAge: 60 * 1000},
  saveUninitialized: false,
     })
  )

passport.use(
  new GoogleStrategy({
  clientID: "process.env.clientID",
  clientSecret: "process.env.clientSecret",
  callbackURL: '/auth/google/callback',
},
async (accessToken, refreshToken, profile, done) => {
  const existingUser = await User.findOne({
    providerId: profile.id,
  })
  if (existingUser) {
      return done(null, existingUser);
  }
  const user = await new User({
    provider: profile.provider,
    providerId: profile.id,
    displayName: profile.displayName,
    
  }).save()
  done(null, user);
 })
)

passport.serializeUser(function (user, done) {
  done(null, user.id);
});

passport.deserializeUser(function (obj, done) {
  done(null, done);
});

My error :

ERROR  Error in fetch(): request to http://localhost:3000/login failed, reason: read ECONNRESET

  at ClientRequest.<anonymous> (node_modules/node-fetch/lib/index.js:1461:11)
  at ClientRequest.emit (events.js:400:28)
  at Socket.socketErrorListener (_http_client.js:475:9)
  at Socket.emit (events.js:400:28)
  at emitErrorNT (internal/streams/destroy.js:106:8)
  at emitErrorCloseNT (internal/streams/destroy.js:74:3)
  at processTicksAndRejections (internal/process/task_queues.js:82:21)

Thank you

almost 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

For starters, move this:

// if user is not logged-in redirect back to login page
app.use(function(req, res, next) {
   if (req.session.user == null){
   res.redirect('http://localhost:3000/login');
   }   else {
    next();
   }
});

to be after this:

app.use(
  session({
  secret: 'keyboard cat',
  resave: false,
  cookie: { httpOnly: false, secure: false, maxAge: 60 * 1000},
  saveUninitialized: false,
     })
)

There will NEVER be a req.session until AFTER the session middleware runs so any code that tries to use req.session must be after the session middleware.

Also change this:

if (req.session.user == null) 

to:

if (!req.session || !req.session.user)

So the code is safe if req.session doesn't exist.

almost 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