Created
February 9, 2025 06:01
-
-
Save SeLub/5b8f8e3b20039f556bdb453f149383fd to your computer and use it in GitHub Desktop.
Revisions
-
SeLub created this gist
Feb 9, 2025 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,85 @@ # How to restrict API access to our backend Here are several approaches to restrict API access to our frontend: ## CORS Policy Configuration: ```tsx import cors from '@fastify/cors'; fastify.register(cors, { origin: ['https://our-frontend-domain.com'], credentials: true, methods: ['GET', 'POST', 'PUT', 'DELETE'] }); ``` Pros: - Simple implementation - Browser-level protection - Standard web security practice - Maintains secure cookie handling Cons: - Only browser-enforced - Can be bypassed by non-browser clients - Requires proper frontend domain configuration ## API Key + Origin Check: ```tsx fastify.addHook('preHandler', async (request, reply) => { const apiKey = request.headers['x-api-key']; const origin = request.headers.origin; if (!isValidApiKey(apiKey) || !isAllowedOrigin(origin)) { reply.code(403).send({ error: 'Unauthorized' }); } }); ``` Pros: - Stronger security than CORS alone - Works with non-browser clients - Can implement rate limiting - Fine-grained access control Cons: - Additional implementation complexity - Key management overhead - Requires secure key storage ## Combined Approach (Recommended): ```tsx // CORS + API Key + JWT fastify.register(cors, { origin: process.env.FRONTEND_URL, credentials: true }); fastify.addHook('preHandler', validateApiKey); fastify.addHook('preHandler', validateOrigin); ``` Pros: - Multiple security layers - Comprehensive protection - Flexible configuration - Best security practices Cons: - More complex setup - Additional request overhead - Requires careful configuration The combined approach provides the best security while maintaining usability for legitimate frontend requests.