Use AI to integrate Auth0
Use AI to integrate Auth0
If you use an AI coding assistant like Claude Code, Cursor, or GitHub Copilot, you can add Auth0 API authentication automatically in minutes using agent skills.Install:Then ask your AI assistant:Your AI assistant will automatically create your Auth0 API, fetch credentials, install
@auth0/auth0-fastify-api, configure the plugin, and protect your API endpoints with JWT validation. Full agent skills documentation →Get Started
This quickstart demonstrates how to protect Fastify API endpoints using JWT access tokens. You’ll build a secure API that validates Auth0 access tokens and grants access to protected resources.Create a new project
Create a new directory for your Fastify API and initialize a Node.js project.Initialize the projectCreate the project structure
Install the Auth0 Fastify API SDK
Install the required dependenciesUpdate your
package.json to add start scripts:package.json
Setup your Auth0 API
Next, you need to create a new API on your Auth0 tenant and add the environment variables to your project.You have two options to set up your Auth0 API: use a CLI command or configure manually via the Dashboard:
- CLI
- Dashboard
Run the following command in your project’s root directory to create an Auth0 API:After creation, copy the Identifier and your Domain values, then create your
.env file:.env
This command will:
- Check if you’re authenticated (and prompt for login if needed)
- Create an Auth0 API with the specified identifier
- Display the API details including the domain and identifier
Configure the Auth0 API plugin
Create your Fastify server and register the Auth0 API plugin:What this does:
server.js
- Registers the Auth0 API plugin with your Auth0 domain and API audience
- Configures JWT validation for incoming requests
- Makes the
requireAuth()preHandler available for protecting routes
Create API routes
Add public and protected routes to your Key points:
server.js:server.js
- Public routes don’t require authentication
- Protected routes use
preHandler: fastify.requireAuth()to require a valid JWT request.usercontains the decoded JWT claims for authenticated requests- The
subclaim contains the user’s unique identifier
Run your API
Start the development server:Your API is now running at http://localhost:3001.
The
--watch flag in Node.js 20+ automatically restarts the server when files change.Test your API
Test the public endpoint (no authentication required):You should see:Test the protected endpoint without a token (should fail):You should see a 401 Unauthorized error:To test with a valid token, you need to:
- Create a client application (web or mobile app) that authenticates users
- Configure the client to request an access token for your API (using the audience parameter)
- Use that access token in the Authorization header
CheckpointYou should now have a protected API. Your API:
- Accepts requests to public endpoints without authentication
- Rejects requests to protected endpoints without a valid token
- Validates JWT tokens against your Auth0 domain and audience
- Provides user information from the token claims via
request.user
Advanced Usage
Custom Token Claims with TypeScript
Custom Token Claims with TypeScript
Extend the Token interface to add type safety for custom claims in your access tokens:Now TypeScript will recognize your custom claims:
server.ts
server.ts
Custom claims must use namespaced URLs (e.g.,
https://myapp.com/roles) unless they’re standard OIDC claims. Learn more about custom claims.Permission-Based Authorization
Permission-Based Authorization
Role-Based Authorization
Role-Based Authorization
CORS Configuration
CORS Configuration
Enable CORS to allow requests from web applications:For production, specify exact origins:
server.js
server.js
Error Handling
Error Handling
Add comprehensive error handling for authentication errors:
server.js
Rate Limiting
Rate Limiting
Protect your API from abuse with rate limiting:
server.js
Troubleshooting
Common Issues and Solutions
Common Issues and Solutions
”No authorization token was found”
Problem: The API cannot find the access token in the request.Solutions:- Ensure the
Authorizationheader is present:Authorization: Bearer YOUR_TOKEN - Check that “Bearer” is included before the token
- Verify the token is not expired
”Invalid token” or “jwt malformed”
Problem: The token format is invalid.Solutions:- Ensure you’re using an access token, not an ID token
- The token should be obtained with your API’s
audienceparameter - Check that the token is a valid JWT (should have three parts separated by dots)
“Invalid signature”
Problem: The token signature doesn’t match.Solutions:- Verify
AUTH0_DOMAINmatches the domain that issued the token - Ensure you’re using RS256 signing algorithm (default)
- Check that the token hasn’t been modified
”Invalid audience”
Problem: The token’s audience doesn’t match your API.Solution: The client application must request a token with the correct audience:CORS errors in browser
Problem: Browser blocks API requests due to CORS policy.Solution: Install and configure@fastify/cors:Next Steps
Now that you have a protected API, consider exploring:- Fastify Web App Quickstart - Build a web application that calls your API
- Role-Based Access Control - Implement fine-grained permissions
- API Authorization Best Practices - Learn about access token best practices
- Monitor Your API - Set up logging and monitoring
Resources
- auth0-fastify-api GitHub - Source code and examples
- Fastify Documentation - Learn more about Fastify
- Auth0 API Authentication - Understanding access tokens
- Auth0 Community - Get help from the community