Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

107
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda