How to Create API Route in SvelteKit: Simple Guide
In SvelteKit, create an API route by adding a file inside the
src/routes folder with a supported HTTP method export like GET or POST. Each exported function handles requests and returns a response object with status and body.Syntax
To create an API route in SvelteKit, you export functions named after HTTP methods (e.g., GET, POST) from a file inside src/routes. Each function receives a RequestEvent and returns a response object.
- GET: Handles GET requests.
- POST: Handles POST requests.
- RequestEvent: Contains request info like URL, params, and body.
- Response: Return an object with
status,headers, andbody.
javascript
export async function GET(event) { return new Response('Hello from GET API route'); } export async function POST(event) { const data = await event.request.json(); return new Response(JSON.stringify({ message: 'Received', data }), { status: 201, headers: { 'Content-Type': 'application/json' } }); }
Example
This example shows a simple API route at src/routes/api/hello/+server.js that responds to GET requests with a greeting message.
javascript
export async function GET() { return new Response(JSON.stringify({ message: 'Hello from SvelteKit API!' }), { status: 200, headers: { 'Content-Type': 'application/json' } }); }
Output
{"message":"Hello from SvelteKit API!"}
Common Pitfalls
- Not naming the file
+server.jsor+server.tsinside the route folder will prevent SvelteKit from treating it as an API endpoint. - Forgetting to export functions named exactly as HTTP methods (
GET,POST, etc.) will cause the route to not respond. - Returning plain objects instead of a
Responseobject can cause errors; always return aResponseor usejson()helper. - Not setting correct
Content-Typeheaders can confuse clients about response format.
javascript
/* Wrong: missing +server.js filename and wrong export */ export function get() { return { message: 'This will not work' }; } /* Right: correct filename and export */ export async function GET() { return new Response('This works'); }
Quick Reference
| Concept | Description |
|---|---|
| File name | Must be named +server.js or +server.ts inside route folder |
| HTTP method exports | Export async functions named GET, POST, PUT, DELETE, etc. |
| Request parameter | Function receives a RequestEvent with request details |
| Response | Return a Response object or use helpers like json() |
| Headers | Set Content-Type header for response format |
Key Takeaways
Create API routes by adding +server.js files inside src/routes folders.
Export async functions named after HTTP methods like GET or POST to handle requests.
Always return a Response object with proper status and headers.
Name the file +server.js or +server.ts exactly to enable API routing.
Set Content-Type headers to inform clients about response data format.