You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node+Express+Passport中req.user会话未定义问题求助

Hey William, let’s figure out why your req.user is showing up as undefined even though your Auth0 flow seems mostly functional. I’ve combed through your code and spotted a few critical issues that are almost certainly causing this—let’s break them down and fix them:

1. Missing CORS Credentials Configuration

Your frontend runs on localhost:3000 and your backend on localhost:8084, which counts as a cross-origin request. By default, the cors() middleware doesn’t allow requests to carry credentials (like your session cookie), so your backend can’t recognize the user’s existing session when /auth/me is called.

Fix this by updating your CORS setup:

// Replace your plain app.use(cors()) with this
app.use(cors({
  origin: process.env.SUCCESS_REDIRECT, // Restrict to your frontend domain for security
  credentials: true // Allow cookies/credentials to be sent cross-origin
}));

And make sure your frontend request includes credentials:

  • If using Axios: axios.get('http://localhost:8084/auth/me', { withCredentials: true })
  • If using Fetch: fetch('http://localhost:8084/auth/me', { credentials: 'include' })

2. Mismatched Passport Serialize/Deserialize Logic

Right now, you’re storing the entire user object in the session with serializeUser, but your deserializeUser is treating that object as a user ID to query the database. That mismatch means your database query is looking for a user with an ID equal to the full user object (which doesn’t exist), so it returns nothing—and req.user ends up undefined.

You have two options to fix this:

This is the standard Passport pattern, as it keeps session data small and efficient:

// Serialize only the user's ID to the session
passport.serializeUser((user, done) => {
  done(null, user.id); // Ensure this matches your user table's primary key
});

// Deserialize by fetching the user from the database using the stored ID
passport.deserializeUser((userId, done) => {
  console.log("Fetching user with ID:", userId); // Debug: confirm this is a valid ID
  app.get("db").find_session_user([userId])
    .then(user => {
      console.log("Database returned:", user); // Debug: check if user exists
      done(null, user[0]);
    })
    .catch(err => {
      console.error("Deserialize error:", err);
      done(err);
    });
});

If you want to keep the full user object in the session, you don’t need to query the database again—just pass it directly to done:

passport.deserializeUser((user, done) => {
  // The session already has the full user object, so no DB call needed
  done(null, user);
});

Your current session cookie has a short maxAge (1 minute) and lacks explicit cross-domain settings. Let’s adjust that for better development and cross-origin support:

app.use(session({
  secret: process.env.SECRET,
  cookie: {
    maxAge: 1000 * 60 * 60 * 24, // Extend to 1 day for easier development
    sameSite: "lax", // Works well for cross-origin requests in development
    secure: process.env.NODE_ENV === "production" // Only use secure cookies in production (HTTPS)
  },
  resave: false,
  saveUninitialized: true
}));

4. Verify Your find_session_user Database Function

Double-check that your PostgreSQL function is correctly accepting a user ID and returning the matching user. For example, it should look something like this:

CREATE OR REPLACE FUNCTION find_session_user(user_id INT)
RETURNS SETOF users AS $$
SELECT * FROM users WHERE id = $1;
$$ LANGUAGE sql;

If the function expects a different data type (like a string instead of an integer) than what you’re passing, it won’t find the user.

Quick Debug Steps

To confirm which issue is causing the problem:

  1. Add console logs in deserializeUser to see what userId you’re passing and what the database returns.
  2. Check your browser’s dev tools > Application > Cookies to ensure the connect.sid cookie is being set and sent with the /auth/me request.

Give these fixes a try—this should get your req.user showing up correctly!

内容的提问来源于stack exchange,提问作者William Hartman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 09:52:56