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:
Option A: Store Only the User ID in Session (Recommended)
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); }); });
Option B: Reuse the Stored User Object (Not Recommended)
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); });
3. Session Cookie Configuration Issues
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:
- Add console logs in
deserializeUserto see whatuserIdyou’re passing and what the database returns. - Check your browser’s dev tools > Application > Cookies to ensure the
connect.sidcookie is being set and sent with the/auth/merequest.
Give these fixes a try—this should get your req.user showing up correctly!
内容的提问来源于stack exchange,提问作者William Hartman

