Add Login to Your Express Application
This guide demonstrates how to integrate Auth0, add authentication, and display user profile information in an Express.js web application using theexpress-openid-connect SDK.
:::note Prerequisites
Before you begin, ensure you have the following installed:
Express Version Compatibility: This quickstart works with Express 4.17.0 and newer.
:::
1. Create a new project
Create a new directory for your Express application and initialize a Node.js project.2. Install the Auth0 Express SDK
Installexpress-openid-connect along with Express and dotenv for environment variable management.
package.json to add start scripts:
📁 package.json
3. Setup your Auth0 App
Next, you need to create a new application on your Auth0 tenant and add the environment variables to your project. You can choose to do this automatically by running a CLI command or manually via the Dashboard: ::::tabs :::tab Run the following shell command in your project’s root directory to create an Auth0 application and generate your.env file:
macOS / Linux:
auth0 login.
:::
:::
:::tab
- Go to the Auth0 Dashboard
- Navigate to Applications → Create Application
- Enter a name for your application (e.g., “My Express App”)
- Select Regular Web Applications and click Create
- In the Settings tab, configure the following:
| Setting | Value |
|---|---|
| Allowed Callback URLs | http://localhost:3000 |
| Allowed Logout URLs | http://localhost:3000 |
- Scroll down and click Save Changes
- Copy the Domain and Client ID values from the Basic Information section
.env file with the following values:
📁 .env
YOUR_AUTH0_DOMAIN with your Auth0 tenant domain (e.g., dev-abc123.us.auth0.com) and YOUR_CLIENT_ID with your application’s Client ID from the dashboard.
:::
Generate a secure secret for session encryption:
SECRET value in your .env file.
:::
::::
4. Configure the middleware
Add the Auth0 middleware to your Express application. Theauth() middleware handles session management and automatically creates /login, /logout, and /callback routes.
📁 index.js
authRequired: falseallows both authenticated and unauthenticated users to access routes by defaultauth0Logout: trueensures users are logged out from Auth0 as well as your app- The middleware automatically provides routes at
/login,/logout, and/callback - User session is stored in an encrypted cookie
5. Create login, logout, and profile routes
Now add routes to display login/logout links and a protected profile page. 📁 index.jsrequiresAuth()middleware protects the/profileroute - unauthenticated users are redirected to loginreq.oidc.usercontains the authenticated user’s profile informationreq.oidc.isAuthenticated()returns a boolean indicating login status- Login and logout routes (
/login,/logout) are automatically created by theauth()middleware
6. Run your app
Start the development server:- Click “Login” - you’re redirected to Auth0’s Universal Login page
- Complete authentication - you’re redirected back to your app
- Visit “/profile” - you see your user information
- Click “Logout” - you’re logged out of both your app and Auth0 :::
Advanced Usage
:::details[Protecting Specific Routes with requiresAuth()] Use therequiresAuth() middleware to protect individual routes that require authentication:
.env file:
offline_access to your scope:
role must be added to your tokens via Auth0 Rules or Actions. Learn more about adding custom claims.
:::
:::
:::details[Custom Session Store (Redis)]
For production environments or when running multiple server instances, use a custom session store:
- Running multiple server instances (load balancing)
- Session data exceeds cookie size limits (~4KB)
- Need session persistence across server restarts
- Using back-channel logout :::
Troubleshooting
:::details[Common Issues and Solutions]“Invalid state” error after login
Problem: State mismatch between the authentication request and callback. Solutions:- Ensure you’re using HTTPS in production
- Check that cookies are being set correctly (not blocked by browser)
- Verify callback URL matches exactly in Auth0 Dashboard
”req.oidc is undefined”
Problem: Theauth() middleware is not applied before accessing req.oidc.
Solution: Ensure app.use(auth(config)) is called before any route that accesses req.oidc:
Session too large / Cookie errors
Problem: User session data exceeds cookie size limits. Solution: Use a custom session store like Redis:Callback URL mismatch
Problem: “Callback URL mismatch” error from Auth0. Solution:- Go to your Auth0 Dashboard → Applications → Your App → Settings
- Add
http://localhost:3000(or your production URL) to Allowed Callback URLs - The URL must match exactly (including trailing slashes)
Environment variables not loading
Problem: Configuration values areundefined.
Solution:
- Ensure
require('dotenv').config()is at the top of your entry file - Verify
.envfile is in the root directory - Check for typos in variable names
Next Steps
Now that you have authentication working, consider exploring:- Add Authorization - Implement role-based access control
- Call Protected APIs - Use access tokens to call your backend APIs
- Customize Universal Login - Brand your login experience
- Add Social Connections - Enable Google, GitHub, and other social logins
- Implement MFA - Add multi-factor authentication
Resources
- express-openid-connect GitHub - Source code and examples
- API Documentation - Complete API reference
- Auth0 Express Sample App - Full sample application
- Auth0 Community - Get help from the community