Get started with Limitly in minutes
npm install @limitly/limitly-js
import { Limitly } from '@limitly/limitly-js'; const limitly = new Limitly({ apiKey: 'lk_1234567890abcdef1234567890abcdef' });
const plan = await limitly.plans.create({ name: 'Basic Plan', description: 'Plan for basic users', max_requests: 10000, request_period: 'month', features: ['api_access', 'basic_analytics'] }); console.log('Created plan:', plan.data?.id);
const user = await limitly.users.create({ name: 'John Doe', email: 'john@example.com', plan_id: plan.data?.id }); console.log('Created user:', user.data?.user_id);
const apiKey = await limitly.apiKeys.create({ name: 'Production API Key', user_id: user.data?.user_id, plan_id: plan.data?.id }); console.log('API Key:', apiKey.data?.api_key);
// In your API middleware app.use(async (req, res, next) => { const userApiKey = req.headers['x-api-key']; if (!userApiKey) { return res.status(401).json({ error: 'API key required' }); } const result = await limitly.validation.validate( userApiKey, req.path, req.method ); if (!result.success) { return res.status(429).json({ error: result.error, details: result.details }); } // Add usage info to response headers res.set('X-RateLimit-Limit', result.details?.limit?.toString()); res.set('X-RateLimit-Remaining', result.details?.remaining?.toString()); res.set('X-RateLimit-Reset', result.details?.reset_time); next(); });
curl -H "X-API-Key: YOUR_USER_API_KEY" \ http://localhost:3000/api/test
X-RateLimit-Limit: 10000 X-RateLimit-Remaining: 9999 X-RateLimit-Reset: 2024-02-01T00:00:00Z
import express from 'express'; import { Limitly } from '@limitly/limitly-js'; const app = express(); const limitly = new Limitly({ apiKey: process.env.LIMITLY_API_KEY! }); // Rate limiting middleware app.use(async (req, res, next) => { const userApiKey = req.headers['x-api-key'] as string; if (!userApiKey) { return res.status(401).json({ error: 'API key required' }); } try { const result = await limitly.validation.validate( userApiKey, req.path, req.method ); if (!result.success) { return res.status(429).json({ error: result.error, details: result.details }); } // Add usage info to response headers res.set('X-RateLimit-Limit', result.details?.limit?.toString()); res.set('X-RateLimit-Remaining', result.details?.remaining?.toString()); res.set('X-RateLimit-Reset', result.details?.reset_time); next(); } catch (error) { console.error('Validation error:', error); return res.status(500).json({ error: 'Internal server error' }); } }); // Your API routes app.get('/api/users', (req, res) => { res.json({ users: [] }); }); app.post('/api/users', (req, res) => { res.json({ message: 'User created' }); }); app.listen(3000, () => { console.log('Server running on port 3000'); });
Was this page helpful?