Skip to content

Latest commit

 

History

History

auth0-express-api

README.md

The Auth0 Express-API SDK is a library for protecting API's in Express applications.

Release Downloads License

📚 Documentation - 🔎 Features - 🚀 Getting Started - 💬 Feedback

Documentation

  • Examples - examples for your different use cases.
  • Docs Site - explore our docs site and learn more about Auth0.

Features

Jump straight to the capability you need.

Feature What it does
Quick start Protect an API with createAuth0Api in a few lines
Environment variables Configure from AUTH0_* env vars instead of hardcoding
Protect an API route (requiresAuth) Require a valid bearer access token
Read token claims (req.auth0.user) Access claims extracted from the verified token
Call another API on behalf of the user Exchange the caller's token for one issued to a downstream API
Call a third party API (Token Vault) Get a Google or Slack access token for the caller from Token Vault
Exchange an external token (Custom Token Exchange) Turn a legacy or partner token into an Auth0 access token
Handle a failed Token Vault exchange Tell a misconfiguration from a tenant refusal with isConnectionExchangeError
Require specific scopes Gate routes with scopesInclude (match all or any)
Authorization with claims Restrict routes with claimEquals, claimIncludes, claimCheck
Custom token / user type Type your custom claims via module augmentation
Custom fetch Swap in your own fetch (proxies, retries, instrumentation)

Getting Started

1. Install the SDK

npm i @auth0/auth0-express-api

This library requires Node.js 22 LTS and newer LTS versions.

3. Register the Auth0 Express API router

Register the Auth0 Express API router with your Express instance.

import express from 'express';
import { createAuth0Api } from '@auth0/auth0-express-api';

const app = express();

app.use(createAuth0Api({
  domain: '<AUTH0_DOMAIN>',
  audience: '<AUTH0_AUDIENCE>',
}));

The AUTH0_DOMAIN can be obtained from the Auth0 Dashboard once you've created an API. The AUTH0_AUDIENCE is the identifier of the API that is being called. You can find this in the API section of the Auth0 dashboard.

Environment Variable Support: You can also configure the SDK using environment variables (AUTH0_DOMAIN, AUTH0_AUDIENCE). See EXAMPLES.md for details.

Protecting API Routes

In order to protect an API route, you can use the requiresAuth middleware:

import { requiresAuth } from '@auth0/auth0-express-api';

app.get(
  '/protected-api',
  requiresAuth(),
  async (req, res) => {
    res.json({ message: `Hello, ${req.auth0.user!.sub}` });
  }
);

The SDK exposes the claims, extracted from the token, as the user property on the req.auth0 object.

Authorization with Claims

Beyond basic authentication, you can authorize requests based on specific token claims:

import {
  requiresAuth,
  claimEquals,
  claimIncludes,
  claimCheck,
  scopesInclude,
} from '@auth0/auth0-express-api';

// Check if a claim equals a specific value
app.get('/admin', requiresAuth(), claimEquals('isAdmin', true), handler);

// Check if a claim includes all specified values
app.get('/admin/edit', requiresAuth(), claimIncludes('roles', 'admin', 'editor'), handler);

// Custom validation logic
app.get('/premium', requiresAuth(), claimCheck(
  (req, token) => token.tier === 'premium' || token.roles?.includes('admin'),
  'Premium tier or admin role required'
), handler);

// Flexible scope matching - match ALL (default) or ANY
app.get('/admin/edit', requiresAuth(), scopesInclude('read:admin write:admin'), handler);
app.get('/messages', requiresAuth(), scopesInclude('read:messages read:admin', { match: 'any' }), handler);

See EXAMPLES.md for more authorization patterns.

Custom Types

In order to use a custom user type to represent custom claims, you can configure the Token type in a module augmentation:

declare module '@auth0/auth0-express-api' {
  interface Token {
    id: number;
    name: string;
    age: number;
  }
}

Doing so will change the user type on the req.auth0.user object automatically:

app.get(
  '/protected-api',
  requiresAuth(),
  async (req, res) => {
    res.json({ message: `Hello, ${req.auth0.user!.name}` });
  }
);

Important

The above is to protect API routes by the means of a bearer token, and not server-side rendering routes using a session.

Feedback

Contributing

We appreciate feedback and contribution to this repo! Before you get started, please read the following:

Raise an issue

To provide feedback or report a bug, please raise an issue on our issue tracker.

Vulnerability Reporting

Please do not report security vulnerabilities on the public GitHub issue tracker. The Responsible Disclosure Program details the procedure for disclosing security issues.

What is Auth0?

Auth0 Logo

Auth0 is an easy to implement, adaptable authentication and authorization platform. To learn more checkout Why Auth0?

This project is licensed under the Apache License 2.0. See the LICENSE file for more info.