API keys and ratelimiting for fastify
This project is a Fastify-based API template integrated with Unkey for API key management and rate-limiting. It uses OpenAI API to generate facts, and implements user authentication and request-limiting features.
Ensure you have the following installed:
src/db/index.ts
)1git clone https://github.com/Vardhaman619/fastify-unkey.git2cd fastify-unkey
1bun install
Copy the .env.example
file and create a .env
file:
1cp .env.example .env
Ensure you fill in all the required environment variables such as:
1SERVER_PORT=30002OPENAI_API_KEY=your_openai_api_key3UNKEY_API_KEY=your_unkey_api_key4UNKEY_API_ID=your-unkey-api-id5TURSO_DATABASE_URL=your-turso-database-url6TURSO_AUTH_TOKEN=your-turso-auth-token
1bun db:generate2bun db:migrate
1bun start
To use the API, you need to generate an API key using Unkey. Once you have the API key, you can make requests to the API using the following format:
POST /signup
1{2 "email": "your_email@example.com",3 "password": "your_password"4}
1{2 "apiKey": "your_api_key"3}
GET /fact
Authorization: Bearer your-api-key
1{2 "headers": {3 "Authorization": "Bearer your-api-key"4 }5}
1{2 "fact": "Did you know...?"3}
Each user is limited to 10 requests per day. Once the limit is reached, the API will return a 429 (Too Many Requests) status code.
GET /facts
Description: Description: Returns all facts generated for today by the authenticated user.
Pre-requisites: Add API Key in headers: Authorization: Bearer your-api-key
1{2 "headers": {3 "Authorization": "Bearer your-api-key"4 }5}
1[2 {3 "fact": "Did you know...?",4 "createdAt": "dd-mm-yyyy"5 },6 {7 "fact": "Did you know...?",8 "createdAt": "dd-mm-yyyy"9 }10]
src/
controllers/
: Manages API request handling (auth and facts).services/
: Business logic related to authentication and facts.middleware/
: Implements rate limiting and authentication middleware.plugins/
: Fastify plugins for authentication and facts handling.db/
: Contains the database schema, migrations, and configuration.lib/
: Library functions for interacting with Unkey and OpenAI.This project is licensed under the MIT License. See the LICENSE file for more information.
2500 verifications and 100K successful rate‑limited requests per month. No CC required.