Adds HTTP headers to page responses from any SvelteKit web application enhancing security for visitors browsing your site.
npm install @faranglao/sveltekit-security-headersTo add HTTP Security Response Headers to a SvelteKit application follow these steps:
-
Install the
@faranglao/sveltekit-security-headerspackage usingnpm install @faranglao/sveltekit-security-headers. -
Add or update src/hooks.server.ts file:
- Scenario: no previous Hooks defined in
src/hooks.server.ts:
import type { Handle } from '@sveltejs/kit';
import { HttpResponseHeaders } from '@faranglao/sveltekit-security-headers';
export const handle: Handle = HttpResponseHeaders.handle;- Scenario: existing Hooks defined in
src/hooks.server.ts:
Use the sequence helper function to wrap the existing hook and HttpResponseHeaders.handle hook as shown below.
import type { Handle } from '@sveltejs/kit';
import { sequence } from '@sveltejs/kit/hooks';
import { HttpResponseHeaders } from '@faranglao/sveltekit-security-headers';
export const handle: Handle = sequence(async ({ event, resolve }) => {
// Do something with the inbound request
const response = await resolve(event);
// Do something with the outbound response before returning it
return response;
}, HttpResponseHeaders.handle);Then run the web application using npm run dev or npm run build && npm run preview.
Source code for the sveltekit-security-headers package is maintained on GitHub.