Loading...
Loading...
Use when securing Fastify API endpoints with JWT Bearer token validation, scope/permission checks, or stateless auth - integrates @auth0/auth0-fastify-api for REST APIs receiving access tokens from frontends or mobile apps.
npx skill4agent add auth0/agent-skills auth0-fastify-apiauth0-quickstart@auth0/auth0-fastifyauth0-reactauth0-vueauth0-angularauth0-nextjsauth0-react-nativenpm install @auth0/auth0-fastify-api fastify dotenv# Using Auth0 CLI
auth0 apis create \
--name "My Fastify API" \
--identifier https://my-api.example.com.envAUTH0_DOMAIN=your-tenant.auth0.com
AUTH0_AUDIENCE=https://my-api.example.comserver.jsimport 'dotenv/config';
import Fastify from 'fastify';
import fastifyAuth0Api from '@auth0/auth0-fastify-api';
const fastify = Fastify({ logger: true });
// Register Auth0 API plugin
await fastify.register(fastifyAuth0Api, {
domain: process.env.AUTH0_DOMAIN,
audience: process.env.AUTH0_AUDIENCE,
});
fastify.listen({ port: 3001 });// Public route - no authentication
fastify.get('/api/public', async (request, reply) => {
return {
message: 'Hello from a public endpoint!',
timestamp: new Date().toISOString(),
};
});
// Protected route - requires valid JWT
fastify.get('/api/private', {
preHandler: fastify.requireAuth()
}, async (request, reply) => {
return {
message: 'Hello from a protected endpoint!',
user: request.user.sub,
timestamp: new Date().toISOString(),
};
});
// Protected route with user info
fastify.get('/api/profile', {
preHandler: fastify.requireAuth()
}, async (request, reply) => {
return {
profile: request.user, // JWT claims
};
});curl http://localhost:3001/api/publiccurl http://localhost:3001/api/private \
-H "Authorization: Bearer YOUR_ACCESS_TOKEN"| Mistake | Fix |
|---|---|
| Created Application instead of API in Auth0 | Must create API resource in Auth0 Dashboard → Applications → APIs |
| Missing Authorization header | Include |
| Wrong audience in token | Client must request token with matching |
| Using ID token instead of access token | Must use access token for API auth, not ID token |
| Not handling 401/403 errors | Implement proper error handling for unauthorized/forbidden responses |
auth0-quickstartauth0-fastifyauth0-mfadomainaudiencerequest.userrequest.user.subfastify.requireAuth()fastify.requireAuth({ scopes: 'read:data' })fastify.requireAuth({ scopes: ['read:data', 'write:data'] })preHandler: fastify.requireAuth()request.user.subrequest.user['namespace/claim']