Sveltekit - Headers



Headers in SvelteKit are important for keeping our application secure, managing content delivery, and controlling caching. This piece of information allows developers to set key HTTP response headers like Content-Security-Policy and Cache-Control, which help improve the application's security and performance.

What are Headers?

Headers are pieces of information that are sent with HTTP requests and responses. They help control how the data is handled by browsers and servers.

Setting Headers

In SvelteKit, you can use the setHeaders function inside a load function to set HTTP response headers. This is important because it helps you control how browsers and servers manage your content.

Syntax

Here is the basic syntax for setting headers in Sveltekit:

export function load({ setHeaders }) {
    setHeaders({
        'Header-Name': 'Header-Value'
    });
}

Multiple Headers: If you want to set multiple headers, you can include them in the same object:

export function load({ setHeaders }) {
    setHeaders({
        'Cache-Control': 'no-store',
        'X-Custom-Header': 'CustomValue'
    });
}

Arrays of Multiple values: To send multiple values for the same header, you can use an array in the following format:

export function load({ setHeaders }) {
    setHeaders({
        'Set-Cookie': ['type=ninja', 'language=javascript']
    });
}

Example

The following is a simple example demonstrating how to set headers in SvelteKit.

<!--src/routes/+page.server.js-->
export function load({ setHeaders }) {
    // Add a console.log to verify this function runs
    console.log('Setting headers...');
    
    setHeaders({
        'X-Custom-Header': 'Hello from SvelteKit',
        'Cache-Control': 'max-age=3600'
    });

    return {
        message: 'Hello World'
    };
}

<!--src/routes/+page.svelte-->
<script>
    export let data;
</script>

<h1>{data.message}</h1>

Output

sveltekit-headers
Advertisements