Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

110
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!