API Key Authentication
The authAPIKey middleware extracts API keys from the x-api-key header or apiKey query parameter and decodes them as JWTs.
Installation
import { authAPIKey } from '@pikku/core/middleware'
Usage
import { authAPIKey } from '@pikku/core/middleware'
wireHTTP({
// ...
middleware: [authAPIKey({ source: 'header' })],
})
Options
| Option | Type | Description |
|---|---|---|
source | 'header' | 'query' | 'all' | Where to look for the API key |
'header'— Reads from thex-api-keyheader only'query'— Reads from theapiKeyquery parameter only'all'— Checks the header first, falls back to query parameter
How It Works
- Extracts the API key from the configured source
- Decodes the key as a JWT using
jwtService.decode() - Sets the decoded payload as the user session
This means API keys are JWTs — you generate them with jwtService.encode() and the middleware decodes them on each request.
Behavior
- Skips if no API key is found (allows unauthenticated routes)
- Skips if a session already exists (allows stacking with other auth middleware)
- Requires a
JWTServicein your singleton services
Example: Generating API Keys
export const createAPIKey = pikkuFunc<{ userId: string }, { apiKey: string }>({
func: async ({ jwt }, data) => {
const apiKey = await jwt.encode(
{ value: 365, unit: 'day' },
{ userId: data.userId }
)
return { apiKey }
},
})