Skip to main content

Auth0 Authentication Guide: Setup, Rules, Actions & M2M Tokens

Auth0 is an identity platform that handles authentication and authorization so you don't have to build it yourself. This guide covers everything from initial tenant setup to production-grade patterns: social connections, Universal Login customization, Actions pipelines, M2M tokens for service-to-service auth, and MFA configuration.

✓ OAuth2 & OIDC compliant ✓ 7,500 MAU free tier ✓ Social + enterprise connections ✓ M2M token support ✓ Extensible Actions pipeline

Why Auth0 Instead of Building Auth Yourself?

Building authentication from scratch means implementing password hashing (bcrypt/Argon2), secure session management, CSRF protection, OAuth2 flows, token rotation, brute-force protection, and MFA — all of which have subtle security failure modes. A single misconfiguration can expose your entire user base. Auth0 provides all of this as a managed service with a battle-tested implementation, leaving your team to focus on product logic instead of identity infrastructure.

Auth0 is ideal when you need: multiple social providers, enterprise SSO (SAML/OIDC), machine-to-machine API authentication, or compliance features like MFA and log retention. For simple username/password apps that never need external providers, a library like Passport.js or a lighter solution like Clerk may be more appropriate.

Tenant Setup and Application Types

An Auth0 tenant is an isolated environment (like a workspace) that holds your users, applications, and settings. Create separate tenants for development, staging, and production. Within a tenant, you register Applications — each represents a client that will authenticate users:

Application Type Use Case Grant Type
Regular Web AppNext.js, Express (server-side)Authorization Code
SPAReact, Vue (client-side)Auth Code + PKCE
Native / MobileiOS, AndroidAuth Code + PKCE
Machine to MachineBackend services, cron jobsClient Credentials

Adding Auth0 to an Express / Next.js App

# Install SDK
npm install @auth0/nextjs-auth0

# .env.local
AUTH0_SECRET='use-a-long-random-string'
AUTH0_BASE_URL='http://localhost:3000'
AUTH0_ISSUER_BASE_URL='https://YOUR_DOMAIN.auth0.com'
AUTH0_CLIENT_ID='your-client-id'
AUTH0_CLIENT_SECRET='your-client-secret'
// pages/api/auth/[auth0].js — catch-all route
import { handleAuth } from '@auth0/nextjs-auth0';
export default handleAuth();

// pages/_app.js
import { UserProvider } from '@auth0/nextjs-auth0/client';
export default function App({ Component, pageProps }) {
  return (
    <UserProvider>
      <Component {...pageProps} />
    </UserProvider>
  );
}

// Protected page
import { withPageAuthRequired } from '@auth0/nextjs-auth0';
export default withPageAuthRequired(function Dashboard({ user }) {
  return <p>Welcome {user.name}</p>;
});

Social Connections (Google, GitHub)

In the Auth0 Dashboard, go to Authentication > Social and enable connections. For Google, create an OAuth2 app in Google Cloud Console and paste your Client ID + Secret. For GitHub, register an OAuth App at github.com/settings/developers. Auth0 normalizes the profile data across all providers into a consistent user object with sub, email, and name fields.

Rules vs Actions: What Changed

Rules were the original Auth0 pipeline extension — JavaScript functions that ran sequentially after every login. Actions replace them with a cleaner, node-module-based system. Key differences:

Feature Rules (deprecated) Actions (current)
npm dependenciesShared, limited listAny npm package
TestingManual onlyBuilt-in test runner
SecretsGlobal configurationPer-action secrets
TriggersLogin onlyLogin, M2M, Registration, etc.
// Auth0 Action: Add custom claim to access token
exports.onExecutePostLogin = async (event, api) => {
  const namespace = 'https://myapp.com';
  const roles = event.authorization?.roles ?? [];
  api.accessToken.setCustomClaim(`${namespace}/roles`, roles);
  api.idToken.setCustomClaim(`${namespace}/roles`, roles);
};

M2M Tokens for Backend-to-Backend Authentication

# Request an M2M access token (Client Credentials flow)
curl -X POST https://YOUR_DOMAIN.auth0.com/oauth/token \
  -H "content-type: application/json" \
  -d '{
    "client_id": "YOUR_M2M_CLIENT_ID",
    "client_secret": "YOUR_M2M_CLIENT_SECRET",
    "audience": "https://api.yourapp.com",
    "grant_type": "client_credentials"
  }'

# Response includes access_token (JWT) and expires_in seconds
# Cache the token; request a new one ~60s before expiry

Validate M2M tokens in your API the same way as user tokens — check the iss, aud, and expiry, and verify the signature using Auth0's JWKS endpoint.

MFA Configuration

Enable MFA under Security > Multi-factor Auth. Auth0 supports TOTP (authenticator apps), SMS, WebAuthn (passkeys/hardware keys), and Duo. Use an Action to enforce MFA programmatically for high-risk users:

// Require MFA for admin users
exports.onExecutePostLogin = async (event, api) => {
  if (event.authorization?.roles?.includes('admin')) {
    api.multifactor.enable('any', { allowRememberBrowser: false });
  }
};

Auth0 vs Clerk vs NextAuth Comparison

Feature Auth0 Clerk NextAuth.js
Free tier7,500 MAU10,000 MAUSelf-hosted (free)
UI componentsUniversal Login (hosted)Drop-in React componentsBuild your own
M2M / Client CredentialsYesLimitedManual implementation
Enterprise SSO (SAML)Yes (paid)Yes (paid)Via providers
Self-hosted optionNoNoYes
Share this tool: X / Twitter LinkedIn
✓ 60,000+ developers use DevPlaybook ★★★★★ 4.8 / 5 on Gumroad ✓ MIT licensed · Instant download ✓ No login required

Related Products

on Gumroad

You Might Also Need

More Free Tools

Enjoying this tool? Get more like it.

Weekly developer tool guides, productivity playbooks & AI tricks. Free. No spam.

DevPlaybook Pro 7 days free

Unlock AI-Powered Dev Tools

  • ⚡ AI Code Review, Doc Generator & SQL Builder
  • ⚡ All premium templates & early access
  • ⚡ Member discounts on Gumroad products
Start Free Trial →

$9/mo after trial · Cancel anytime

Want the full toolkit?

Get DevPlaybook Pro

Every template, guide, boilerplate, and automation script in one bundle. 13 premium products — grab them all at once and save big.

$79
$241 separately Save $162 (67% off)
Get DevPlaybook Pro — $79 →

MIT licensed · Instant download · No subscription

See what's included → Browse all deals →