New to Rust? Grab our free Rust for Beginners eBook Get it free →
Facebook Login with Node.js and Express

People signing in with Facebook need a way to return to your app after authorizing it. Facebook Login sends the browser to Facebook and back to a callback on your server, while Express sessions keep the sign-in across requests.
This article explains Express’s role in the flow and walks through setting up the callback and session-backed login.
TL;DR
Facebook Login in Express sends the browser to Facebook, handles the callback with Passport, and stores the signed-in user in an application session.
- Register an exact callback URL and keep the app secret on the server.
- Use Passport’s Facebook strategy for the authorization redirect and callback.
- Store a local user ID in the session, not a provider access token or whole profile.
- Use HTTPS and a persistent session store outside local development.
What Facebook Login does in an Express app
Facebook Login lets a person authorize an app through Facebook, then redirects the browser back to your server. Passport handles the provider exchange, while Express session middleware remembers the sign-in across requests.
| Part | Responsibility |
|---|---|
| Facebook app | Defines credentials and allowed redirect settings |
| Passport strategy | Starts authentication and handles the provider callback |
| Express session | Maintains the app’s signed-in state between requests |
| Local user table | Stores your account and authorization data |
What Express.js contributes to login
Express.js is a web framework for Node.js that maps HTTP requests to route handlers and middleware functions. It lets the app define these request paths without replacing the Node.js runtime.
Why choose Express for this flow?
Express fits a Node.js service when its team can manage middleware order and session persistence in the existing application.
For a browser, a protected page can redirect a signed-out visitor to login. A JSON API can return an authentication error instead, so keep each endpoint’s response contract clear.
For a broader discussion of whether to use the framework in a Node.js project, see CodeForGeek’s Node.js vs Express.js guide.
How to add Facebook Login to an Express app
Attach the Facebook strategy and authentication routes to the Express app that owns this sign-in flow.
Prerequisites for an Express login route
Before adding the provider strategy, confirm that the project can start an Express server and that the team controls the Facebook app configuration. Prepare these pieces:
- A supported Node.js project, with a browser and local server for the authorization redirect.
- A production session store rather than process memory.
Getting started in an existing Express project
Find the file that creates the Express app and registers middleware. Add session handling before Passport’s session support, then register authentication routes after both are initialized. This ordering lets the callback request read the session for its browser.
Express matches a route using both the HTTP method and path. That is why the login and callback use GET handlers, while the logout action uses POST. A handler can redirect, send a response or pass control to another handler.
| Express piece | Role in a route |
|---|---|
| App listener | Accepts requests on the port selected by the application |
| Method and path | Choose a handler for a request such as GET /auth/facebook |
| Middleware | Runs shared request work before the route handler |
| Route parameter | Captures a named path segment in req.params |
A Hello World route is a simple Express endpoint that sends a response to a GET request at the home path. A basic app creates its application instance and registers routes before its listener accepts requests. The code below assumes your project already has that startup file, so add the strategy and routes before listening.
The official Express routing guide distinguishes named path parameters from query parameters, while Passport processes the OAuth callback values instead of trusting them as account data.
Built-in middleware for a larger Express app
Express provides middleware for common request formats and static assets, separate from the Passport strategy used for login.
| Middleware | Use |
|---|---|
| express.json | Parse JSON request bodies for API routes |
| express.urlencoded | Parse URL-encoded form bodies |
| express.static | Serve files such as public stylesheets and images |
Mount body parsers before handlers that read request data. Static assets that do not need a signed-in session can be served separately from account routes, which should keep their access checks.
The Passport callback is a GET route, so a JSON body parser does not read its OAuth response. That response arrives through the URL and is handled by the strategy. Add parsers only where API routes accept JSON or form submissions.
As the entry file grows, group authentication endpoints in an Express router module such as routes/auth.js and mount it in the main app.
Step 1: Register the Facebook app and callback
Create or select a Facebook app in the Meta developer console and enable the Facebook Login product for the app type you are building. The callback URI must match the value passed to Passport, including its scheme, hostname, path and port. Use HTTPS for the production hostname.
For local development, use the supported local redirect configuration shown in the app dashboard. Check the current app mode and allowed-domain settings in Meta’s Facebook Login documentation, since dashboard labels change over time.
Meta’s manual login flow uses a random state value that the app verifies when the browser returns, tying the callback to the request that began login. In a Passport integration, use the strategy’s supported state handling rather than treating callback query values as proof of login.
Step 2: Install Express and the server dependencies
Install Express, Passport, the Facebook strategy and express-session in your project. Use a supported Node.js release and save dependencies in the project’s package manifest so another developer can reproduce the setup.
npm install express passport passport-facebook express-session
The install command adds packages to the current project rather than every Node application on the machine. Keep its package manifest and npm lockfile in version control so a clean deployment can restore the dependency tree used by the project.
Use the import syntax that matches the project’s module system, whether CommonJS or ES modules.
Step 3: Keep credentials and session settings outside source code
Set the Facebook app ID, app secret, callback URL and session secret in the deployment environment or a local environment file excluded from source control. The app ID identifies the Facebook app, its secret authenticates the server to the provider, and a separate random session secret signs the browser’s cookie.
FACEBOOK_APP_ID=your-app-id
FACEBOOK_APP_SECRET=your-app-secret
FACEBOOK_CALLBACK_URL=https://example.com/auth/facebook/callback
SESSION_SECRET=use-a-long-random-value
Step 4: Configure the strategy and session
Use the provider ID in the returned profile to find or create a local user, then complete authentication with that record. The persistence function below stands for your own database query.
const express = require('express');
const session = require('express-session');
const passport = require('passport');
const FacebookStrategy = require('passport-facebook').Strategy;
const app = express();
passport.use(new FacebookStrategy({
clientID: process.env.FACEBOOK_APP_ID,
clientSecret: process.env.FACEBOOK_APP_SECRET,
callbackURL: process.env.FACEBOOK_CALLBACK_URL
}, async (accessToken, refreshToken, profile, done) => {
try {
const user = await findOrCreateUser({
provider: 'facebook',
providerId: profile.id,
displayName: profile.displayName
});
done(null, user);
} catch (error) {
done(error);
}
}));
passport.serializeUser((user, done) => done(null, user.id));
passport.deserializeUser(async (id, done) => {
try {
done(null, await findUserById(id));
} catch (error) {
done(error);
}
});
app.use(session({
secret: process.env.SESSION_SECRET,
resave: false,
saveUninitialized: false,
cookie: {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'lax'
}
}));
app.use(passport.initialize());
app.use(passport.session());
Define the database functions before running this sample. In production, configure a persistent session store instead of express-session’s in-memory default, which is intended for development and does not provide durable multi-process sessions. CodeForGeek’s guide to managing sessions in Node.js and Express covers session setup separately.
The browser cookie carries a session identifier, while the store keeps its associated session data on the server. HttpOnly prevents browser JavaScript from reading the cookie, and Secure limits it to HTTPS requests. These flags do not grant access to a protected route, so keep the route’s authentication check in place.
Step 5: Add login, callback and protected routes
The login route starts the redirect. The callback route lets Passport finish authentication, and a protected route checks the resulting session before returning private data.
app.get('/auth/facebook', passport.authenticate('facebook'));
app.get('/auth/facebook/callback',
passport.authenticate('facebook', {
failureRedirect: '/login'
}),
(req, res) => res.redirect('/account')
);
app.get('/account', (req, res) => {
if (!req.isAuthenticated()) return res.redirect('/login');
res.send(`Signed in as ${req.user.displayName}`);
});
app.post('/logout', (req, res, next) => {
req.logout(error => {
if (error) return next(error);
req.session.destroy(error => {
if (error) return next(error);
res.clearCookie('connect.sid');
res.redirect('/');
});
});
});
Passport’s logout API is callback-based in current versions, so handle its error rather than assuming the session has already been cleared. Use a POST route for logout and protect it against cross-site request forgery as appropriate for the app.
The example clears Express session’s default cookie name. If you customize that name in session settings, pass the same name to clearCookie during logout so the browser does not keep sending an obsolete identifier.
Destroying the Express session signs the person out of your application. It does not revoke permission granted to Facebook, so provider-token revocation and local logout should remain separate actions.
Step 6: Verify the callback and session locally
Start the app with all four environment values set, open the login route in a browser and complete the provider flow. Check that the browser reaches the callback route and that the protected route recognizes the signed-in account on a later request.
If the callback fails, compare the server error category with the route and app settings before changing requested permissions.
Facebook Login errors and production checks
Start with the symptom and check the boundary that owns it. A redirect error points to provider configuration, while a lost sign-in points to Express session ordering, cookie delivery or session storage.
| Symptom | Check | Correction |
|---|---|---|
| Redirect URI mismatch | Compare complete URI strings, including scheme and path | Make dashboard and server values identical |
| Callback succeeds but user is logged out | Confirm session middleware precedes Passport session middleware | Use the same persistent store across app instances |
| Email is absent | Check requested permissions and account-provided fields | Treat email as optional and ask the user to provide it if required |
| Works locally, fails behind proxy | Check HTTPS termination and Express proxy trust | Configure trusted proxy handling and secure cookies carefully |
| New sessions disappear after restart | Check whether the in-memory store is in use | Configure a production session store |
Facebook profile fields depend on permissions, app review requirements and the user’s account. Treat email as optional unless your product requires it, and provide another way for a person to supply an address when necessary.
When a reverse proxy terminates TLS, Express must recognize the trusted proxy before it can send secure cookies. Limit that trust to infrastructure you control, because forwarded protocol and client IP values are otherwise untrusted.
Request only permissions the feature uses. Store an access token only when the app needs it for Facebook API calls, and document how users can unlink the provider or remove their account.
Conclusion
Keep the provider identity, your application’s user record and the browser session as separate parts of the design. Once the callback works locally, verify the deployed hostname, proxy and session store using the same routes that the application will serve.
For the protocol and settings, see Meta’s Facebook Login docs and the Passport Facebook strategy reference. For session cookie and store options, consult Express session middleware documentation.
FAQ
These answers cover the provider choice, callback URL, returned profile data and session storage.




