★ Backend ★
Building an API Proxy with SvelteKit
How to securely consume third-party APIs using SvelteKit server routes — hide API keys and add custom logic on the server.
Why Use an API Proxy?
When building web applications that consume third-party APIs, you often face two problems:
1. Security — API keys should never be exposed to the client
2. CORS — Many APIs don't allow direct browser requests
SvelteKit server routes solve both problems elegantly.
Creating a Proxy Endpoint
Create a file at src/routes/api/proxy/+server.ts:
import { json, error } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
const API_KEY = process.env.THIRD_PARTY_API_KEY;
const BASE_URL = 'https://api.example.com';
export const GET: RequestHandler = async ({ url }) => {
const endpoint = url.searchParams.get('endpoint');
if (!endpoint) {
throw error(400, 'Missing endpoint parameter');
}
const response = await fetch(`${BASE_URL}/${endpoint}`, {
headers: {
'Authorization': `Bearer ${API_KEY}`,
'Content-Type': 'application/json',
},
});
if (!response.ok) {
throw error(response.status, 'Upstream API error');
}
const data = await response.json();
return json(data);
};
Using the Proxy from the Client
Now your frontend can call your own API instead of the third-party one directly:
const response = await fetch('/api/proxy?endpoint=users');
const data = await response.json();
Adding Rate Limiting
You can add rate limiting logic directly in your server route:
const requestCounts = new Map<string, number>();
export const GET: RequestHandler = async ({ url, getClientAddress }) => {
const ip = getClientAddress();
const count = requestCounts.get(ip) ?? 0;
if (count > 100) {
throw error(429, 'Too many requests');
}
requestCounts.set(ip, count + 1);
// ... rest of handler
};
Conclusion
SvelteKit server routes give you a clean, secure way to proxy any third-party API. Your API keys stay on the server, CORS is a non-issue, and you can add custom logic like caching, rate limiting, or data transformation along the way.