@fracabu/fastify-api-key
v1.0.2
Published
Complete API Key authentication for Fastify with scopes, multiple sources, and TypeScript support
Maintainers
Readme
Overview
:gb: English
Features
- Fastify v5 support
- TypeScript-first with complete type definitions
- Multiple extraction sources (header, query, body, cookie)
- Scopes/permissions system
- Rate limiting information support
- Timing-safe key comparison (prevents timing attacks)
- Custom error handlers
- ESM and CJS dual module support
Install
npm install @fracabu/fastify-api-keyQuick Start
import Fastify from 'fastify'
import fastifyApiKey from '@fracabu/fastify-api-key'
const app = Fastify()
await app.register(fastifyApiKey, {
validate: async (key) => {
const apiKey = await db.apiKeys.findByKey(key)
if (!apiKey) return { valid: false }
return { valid: true, scopes: apiKey.scopes }
}
})
// Protected route
app.get('/api/users', {
preHandler: app.apiKey()
}, async (request) => {
return { users: [] }
})
// Route with required scopes
app.delete('/api/users/:id', {
preHandler: app.apiKey({ scopes: ['admin', 'users:delete'] })
}, handler)Utilities
import { generateApiKey, timingSafeCompare } from '@fracabu/fastify-api-key'
const key = generateApiKey({ prefix: 'myapp', length: 32 })
// => 'myapp_aBcDeFgHiJkLmNoPqRsTuVwXyZ012345':it: Italiano
Funzionalita
- Supporto Fastify v5
- TypeScript-first con definizioni di tipo complete
- Sorgenti di estrazione multiple (header, query, body, cookie)
- Sistema scopes/permessi
- Supporto informazioni rate limiting
- Confronto chiavi timing-safe (previene timing attacks)
- Error handler personalizzati
- Supporto modulo duale ESM e CJS
Installazione
npm install @fracabu/fastify-api-keyQuick Start
import Fastify from 'fastify'
import fastifyApiKey from '@fracabu/fastify-api-key'
const app = Fastify()
await app.register(fastifyApiKey, {
validate: async (key) => {
const apiKey = await db.apiKeys.findByKey(key)
if (!apiKey) return { valid: false }
return { valid: true, scopes: apiKey.scopes }
}
})
// Rotta protetta
app.get('/api/users', {
preHandler: app.apiKey()
}, async (request) => {
return { users: [] }
})
// Rotta con scopes richiesti
app.delete('/api/users/:id', {
preHandler: app.apiKey({ scopes: ['admin', 'users:delete'] })
}, handler)Requirements
- Node.js >= 20.0.0
- Fastify >= 5.0.0
License
MIT
