Utilities for creating JSON and text responses, and normalizing URLs to handle SvelteKit's internal URL transformations.
Create a JSON Response object with proper content-type header.
/**
* Creates a JSON Response with proper content-type header
* @param data - Data to serialize as JSON
* @param init - Optional Response initialization (status, headers, etc.)
* @returns Response object with JSON body
*/
function json(data: any, init?: ResponseInit): Response;Usage Examples:
import { json } from '@sveltejs/kit';
import type { RequestEvent } from '@sveltejs/kit';
// Basic JSON response
export async function GET() {
return json({ message: 'Hello, world!' });
}
// With custom status and headers
export async function POST(event: RequestEvent) {
const data = await event.request.json();
const result = await processData(data);
return json(result, {
status: 201,
headers: {
'X-Custom-Header': 'value'
}
});
}
// Error response
export async function DELETE({ params }: { params: { id: string } }) {
const deleted = await deleteItem(params.id);
if (!deleted) {
return json(
{ error: 'Item not found' },
{ status: 404 }
);
}
return json({ success: true });
}
// Return from load function
export async function load() {
const data = await fetchData();
// Note: typically you'd just return the object in load functions
// json() is more useful in API routes
return json(data);
}Create a text/plain Response object.
/**
* Creates a text Response with text/plain content-type
* @param body - Text content
* @param init - Optional Response initialization (status, headers, etc.)
* @returns Response object with text body
*/
function text(body: string, init?: ResponseInit): Response;Usage Examples:
import { text } from '@sveltejs/kit';
// Plain text response
export async function GET() {
return text('Hello, world!');
}
// CSV response (override content-type)
export async function GET() {
const csvData = 'name,age\nAlice,30\nBob,25';
return text(csvData, {
headers: {
'Content-Type': 'text/csv',
'Content-Disposition': 'attachment; filename="data.csv"'
}
});
}
// Custom status
export async function GET({ url }) {
const message = url.searchParams.get('message');
if (!message) {
return text('Missing message parameter', { status: 400 });
}
return text(`Received: ${message}`);
}Strip SvelteKit-internal suffixes from URLs to get the canonical URL.
/**
* Strips SvelteKit-internal suffixes from URLs
* @param url - URL or string to normalize
* @returns Object with normalized URL, flag indicating if it was normalized, and denormalize function
* @since 2.18.0
*/
function normalizeUrl(url: URL | string): {
url: URL;
wasNormalized: boolean;
denormalize: (url?: URL | string) => URL;
};Usage Examples:
import { normalizeUrl } from '@sveltejs/kit';
export async function handle({ event, resolve }) {
// Normalize the request URL to remove internal suffixes
const { url, wasNormalized, denormalize } = normalizeUrl(event.url);
if (wasNormalized) {
console.log('Original URL had SvelteKit suffix:', event.url.href);
console.log('Normalized URL:', url.href);
}
// Use normalized URL for logic
if (url.pathname === '/api/special') {
// Handle special case
}
const response = await resolve(event);
// Denormalize if needed
if (wasNormalized) {
const denormalizedUrl = denormalize(new URL('/some-path', url.origin));
console.log('Denormalized URL:', denormalizedUrl.href);
}
return response;
}
// In a load function
export async function load({ url }) {
const { url: normalizedUrl } = normalizeUrl(url);
// Use normalized URL for comparisons
if (normalizedUrl.pathname.startsWith('/admin')) {
// Admin logic
}
return {};
}interface ResponseInit {
status?: number;
statusText?: string;
headers?: HeadersInit;
}
type HeadersInit =
| Headers
| Record<string, string>
| [string, string][];json() automatically sets Content-Type: application/json and Content-Length headerstext() automatically sets Content-Length header (but NOT content-type)normalizeUrl() is useful in hooks and adapters where you need to handle canonical URLsstatus: HTTP status code (default: 200)statusText: Status message (default based on status code)headers: Response headers as Headers object, Record, or array of tuples