Free 20-minute strategy call with a senior engineer: AI, payments, eLearning or custom software
Engineering

Node.js Authentication with Auth0: A Comprehensive Guide

Node.js Authentication with Auth0: A Comprehensive Guide

In short

Add Auth0 login to a Node.js Express app with express-openid-connect, protect APIs with express-oauth2-jwt-bearer, manage users and follow token best practices.

Building secure login yourself means handling password storage, multi-factor authentication, social logins, token expiry and a long list of attacks. Auth0 (by Okta) takes that work off your hands with a hosted identity platform. This guide shows how to add Auth0 authentication to a Node.js and Express app using Auth0’s current SDKs: login and logout for web apps with express-openid-connect, protecting APIs with JWT access tokens using express-oauth2-jwt-bearer, and the best practices that keep it secure.

What is Auth0?

Auth0 is an identity-as-a-service platform. Your app redirects users to Auth0’s Universal Login page, Auth0 authenticates them (password, social login, passkeys, MFA or enterprise SSO) and sends them back with tokens based on the OpenID Connect (OIDC) and OAuth 2.0 standards.

Why use Auth0 with Node.js?

  • Security handled for you: password hashing, breached-password detection, brute-force protection and MFA.
  • Social and enterprise login (Google, Microsoft, Apple, SAML, Azure AD / Entra ID) without custom code.
  • Standards-based tokens that work across web, mobile and APIs.
  • User management, roles and permissions in one dashboard.
  • Official SDKs for Express that take only a few lines to configure.

Step 1: set up Auth0

  1. Create an Auth0 account and a tenant.
  2. Create an Application of type *Regular Web Application* for an Express app with server-rendered pages.
  3. In the application settings, set Allowed Callback URLs to http://localhost:3000/callback and Allowed Logout URLs to http://localhost:3000.
  4. Note the Domain, Client ID and Client Secret.
  5. If you will protect an API, create an API under Applications → APIs and note its Identifier (audience).

Step 2: create the Express app

mkdir node-auth0-app && cd node-auth0-app
npm init -y
npm install express express-openid-connect dotenv

Create a .env file (never commit it):

ISSUER_BASE_URL=https://YOUR_TENANT.auth0.com
CLIENT_ID=your-client-id
CLIENT_SECRET=your-client-secret
BASE_URL=http://localhost:3000
SECRET=a-long-random-string-for-session-encryption

Step 3: add login and logout

express-openid-connect adds /login, /logout and /callback routes and manages an encrypted session cookie:

require('dotenv').config();
const express = require('express');
const { auth, requiresAuth } = require('express-openid-connect');

const app = express();

app.use(
  auth({
    authRequired: false,
    auth0Logout: true,
    issuerBaseURL: process.env.ISSUER_BASE_URL,
    baseURL: process.env.BASE_URL,
    clientID: process.env.CLIENT_ID,
    clientSecret: process.env.CLIENT_SECRET,
    secret: process.env.SECRET,
  })
);

app.get('/', (req, res) => {
  res.send(req.oidc.isAuthenticated() ? 'Logged in' : 'Logged out');
});

app.get('/profile', requiresAuth(), (req, res) => {
  res.json(req.oidc.user);
});

app.listen(3000, () => console.log('http://localhost:3000'));

Visit /login to sign in through Auth0, then /profile to see the user’s claims. requiresAuth() redirects anonymous users to login.

Free resource

Upgrade and patching checklist

Want this applied to your project? Our engineers will send it with notes for your stack.

Get it free

Step 4: protect an API with access tokens

For APIs used by single-page apps, mobile apps or other services, validate JWT access tokens instead of sessions:

npm install express-oauth2-jwt-bearer
const { auth: checkJwt, requiredScopes } = require('express-oauth2-jwt-bearer');

const verifyToken = checkJwt({
  audience: 'https://api.example.com',
  issuerBaseURL: process.env.ISSUER_BASE_URL,
});

app.get('/api/orders', verifyToken, requiredScopes('read:orders'), (req, res) => {
  res.json({ orders: [], user: req.auth.payload.sub });
});

The middleware downloads Auth0’s public keys, verifies the token signature, issuer, audience and expiry, and rejects invalid tokens with a 401. Clients obtain access tokens from Auth0 by requesting your API’s audience during login.

Step 5: call the Auth0 Management API (optional)

To manage users from your back end, use a Machine-to-Machine application and the official SDK:

npm install auth0
const { ManagementClient } = require('auth0');

const management = new ManagementClient({
  domain: 'YOUR_TENANT.auth0.com',
  clientId: process.env.M2M_CLIENT_ID,
  clientSecret: process.env.M2M_CLIENT_SECRET,
});

const users = await management.users.getAll();

Grant the M2M application only the Management API scopes it needs.

Understanding Auth0 tokens

TokenPurposeWho reads it
ID tokenProves who the user is (name, email) after loginYour client application
Access tokenAuthorises calls to an API with specific scopesYour API, which must verify it
Refresh tokenGets new access tokens without asking the user to log in againYour application, stored securely

Never trust a token you have only decoded. Always verify the signature, issuer, audience and expiry, which the SDK middleware does for you.

Roles and permissions

Use Auth0’s Role-Based Access Control (RBAC) for your API, add permissions such as read:orders and write:orders, assign them to roles, and check them in your routes with requiredScopes or by inspecting req.auth.payload.permissions.

Best practices

  • Keep secrets in environment variables or a secrets manager, never in source code.
  • Use HTTPS in production and set BASE_URL to your real domain.
  • Enable MFA and consider passkeys for stronger, simpler login.
  • Request only the scopes you need, and keep access tokens short-lived.
  • Configure Allowed Callback, Logout and Web Origins precisely; avoid wildcards.
  • Monitor Auth0 logs and set up alerts for suspicious activity.
  • Keep SDKs up to date.

Frequently asked questions

Which Auth0 SDK should I use with Express? Use express-openid-connect for server-rendered web apps with login sessions, and express-oauth2-jwt-bearer to protect APIs with access tokens.

Can I still use passport-auth0? Older apps often use Passport with the Auth0 strategy, but Auth0’s own Express SDKs are simpler and recommended for new projects.

How do I protect a Node.js API with Auth0? Create an API in Auth0, then use express-oauth2-jwt-bearer middleware with your API’s audience and issuer to verify access tokens on each request.

Is it safe to decode JWTs with jsonwebtoken.decode? Decoding alone does not verify a token. Always validate the signature and claims, using the Auth0 SDK middleware or a library such as jose.

Is Auth0 free? Auth0 offers a free plan for small projects, with paid plans for more users and advanced features. Check Auth0’s current pricing.

Need secure authentication in your app?

Vibidsoft builds Node.js back ends, APIs and apps with secure authentication, SSO and role-based access. See our Node.js development services and API integration services, or contact us.

Vibidsoft Engineering Team

Senior engineers who have shipped 450+ projects since 2014 across AI, payments, eCommerce, eLearning and custom software. Every guide is written and reviewed by the people who do the work.

Follow us on LinkedIn · About Vibidsoft

Next step

Talk to an engineer about Modernize & Rescue

Fixed-price upgrades for ageing PHP, Drupal, Magento or hybrid apps, with security patching and a care plan. from $5,000.

  • A 20-minute call with a senior engineer, not a salesperson
  • A written next-step plan within one business day
  • NDA on request
Book a call WhatsApp