Join our Newsletter — 33% off our NHI Course
Home› Guides› SvelteKit Security Guide: CSRF Origin Checks, Hooks, CSP…
Guide Application Security

SvelteKit Security Guide: CSRF Origin Checks, Hooks, CSP and Form Actions Done Right

PDF for newsletter subscribers · free to read online

← All guides
By NHI Mgmt Group, under the editorial direction of Lalit Choda Updated 18 November 2026 15 min read
On this page

SvelteKit gives you a built-in CSRF origin check, a CSP generator and a strict boundary for server-only code, but authentication, authorisation and input validation are still yours to write in every load function, form action and endpoint. This guide explains the SvelteKit security model as described in the official documentation in November 2026, shows where each control lives (configuration, hooks, load functions, form actions and remote functions), and lists the failure patterns that most often turn a SvelteKit app into a data leak. It also summarises the 2026 framework advisories so you can check your patch level.

For general React and Next.js patterns, and for cross-framework topics such as XSS and third-party scripts, see the React and Next.js Security Guide. This page stays specific to SvelteKit.

Key takeaways

  • SvelteKit checks the Origin header on form submissions in production. Keep that protection on and use csrf.trustedOrigins for named exceptions, never '*'.
  • The handle hook in hooks.server is where sessions are resolved into event.locals. It is not, on its own, an authorisation layer for every piece of data.
  • All load functions on a page run concurrently, so a check in a parent layout does not reliably protect a child page's data. Check access where the data is fetched.
  • Everything a server load returns is serialised to the browser. Return only the fields the page needs.
  • Use the built-in kit.csp configuration with mode: 'auto' so SvelteKit adds hashes or nonces for its own inline scripts and styles.
  • Keep secrets in server-only modules and private environment modules. SvelteKit refuses to bundle them into browser code, but only for code inside your project.
  • Several 2026 advisories hit remote functions, adapters and request parsing. Track the framework and adapter versions as closely as your own code.

The SvelteKit trust model

A SvelteKit app mixes code that runs in three places, and the security of the app depends on knowing which is which.

CodeWhere it runsTrust level
+page.server, +layout.server, +server endpoints, hooks.server, remote functions, .server modulesServer onlyMay hold secrets and talk to databases. Must treat all request input as hostile.
+page, +layout universal load functions, hooks (universal), shared modulesServer and browserShipped to users. No secrets, no privileged logic.
Svelte components, hooks.clientBrowser (and server for rendering)Fully visible and modifiable by the user.

The documentation is explicit that server load functions always run on the server, while a load function in a +page.js file runs on both the server and the browser. Database access, API calls that need credentials and authorisation decisions belong in the server-only column. A check that only happens in a component or a universal load function is a user interface feature, not a security control.

Two other facts shape the model. First, the data returned from a server load is serialised and sent to the client, so the return value is effectively a public API response. Second, SvelteKit runs all load functions for a page concurrently, which matters for where authorisation lives (covered below).

CSRF protection and origin checks

SvelteKit's CSRF defence is an origin check on form submissions. According to the configuration reference, csrf.checkOrigin (default true) checks the incoming origin header for POST, PUT, PATCH and DELETE form submissions and verifies that it matches the server's origin. Disabling it lets other origins submit forms to your app. The option is deprecated and is removed in SvelteKit 3.0, where the documented replacement for turning the check off is trustedOrigins: ['*'].

csrf.trustedOrigins (default empty) lists origins that may make cross-origin form submissions. Entries must be full origins including the protocol, such as a payment provider's callback origin. The documentation says including '*' trusts all origins and is generally not recommended.

Practical points:

  • Do not disable the check to fix a broken integration. Add the specific origin to trustedOrigins, record why, and review the list.
  • Know what it covers. The SvelteKit configuration docs describe the check as applying to POST, PUT, PATCH and DELETE form submissions, and name application/x-www-form-urlencoded, multipart/form-data and text/plain as the content types cross-origin requests can use. CSRF checks apply in production, not local development. JSON endpoints in +server files called with fetch rely on browser CORS behaviour and on how your session cookies are scoped. Do not accept form content types on JSON endpoints, and keep state-changing endpoints off GET.
  • The check only runs in production. The documentation states that CSRF checks do not apply in local development, so test the behaviour against a production build.
  • Use SameSite cookies as a second layer. Cookies set with cookies.set are httpOnly and secure by default (except in development). Set sameSite deliberately, typically lax for session cookies.

The CSRF Prevention Guide explains token and origin based defences in general terms, and CORS vs CSRF Protection covers why CORS does not stop form posts.

Hooks: sessions, locals and outbound fetch

handle

The handle hook in src/hooks.server runs for every server request, including during prerendering, and decides the response. Static assets bypass it. Typical security uses are resolving the session cookie into a user and storing it in event.locals, rejecting requests early (rate limits, blocked clients, maintenance mode), and setting security headers on the response. Multiple handlers can be chained with sequence, which keeps authentication, headers and logging in separate, testable functions.

Two cautions from the documentation:

  • If a form action sets or deletes the session cookie, you must update event.locals yourself, because handle does not run again before the page's load functions after the action.
  • Some response headers are immutable (for example on responses created by Response.redirect()), so header changes can throw. Build redirects with SvelteKit's redirect helper and test header logic on redirect paths.

A blanket path check in handle (for example rejecting unauthenticated requests to /admin) is a useful coarse gate, but route matching by string prefix is fragile. Keep fine-grained checks next to the data.

handleFetch

handleFetch lets you modify or replace the result of an event.fetch call that runs on the server, for example to send a request directly to an internal API instead of the public URL. Credential forwarding is the security-relevant part. For same-origin requests, cookie and authorization headers are forwarded unless credentials is set to omit. For cross-origin requests, cookies are included when the target is a subdomain of the app's domain. Review every place that rewrites URLs in handleFetch so that user-controlled input cannot redirect a credentialed request to an unexpected host.

handleError

handleError runs on unexpected errors during loading, rendering or responding. The documentation says it must never throw and that for unknown errors the error value may contain information unsafe to expose. Log the full error server side with a correlation ID, and return only a generic message and that ID to the user.

reroute and init

reroute changes which route a URL maps to before handle runs, without changing event.url. If you use it, make sure any path-based checks in handle use the route that will actually execute, not the original URL. init runs once at server start and suits tasks such as opening database connections with credentials from the private environment.

Load functions and authorisation

The single most important SvelteKit-specific rule: because all load functions for a page run concurrently, an authorisation check in +layout.server is not a guarantee that a child +page.server load has not already fetched and returned protected data. The documentation's own example performs the check in the server load that needs it, throwing an error(401) or error(403) when locals.user is missing or lacks rights.

Apply these rules in every server load:

  • Read identity from event.locals, populated in handle. Never from URL parameters, query strings or form fields. The documentation warns never to use request values such as params or url to decide whether a user is authorised.
  • Authorise the specific object, not just the route. Loading /orders/[id] must confirm the order belongs to the user, which is the classic broken object level authorisation case.
  • Return a minimal, explicit object. Map database rows to the fields the page renders, so password hashes, internal flags and other users' data never reach the serialiser.
  • Do not swallow error() or redirect() in a try block. The documentation warns that catching the thrown value prevents SvelteKit from handling it, which can turn a denied request into a rendered page.
  • Remember that layout server data flows into child pages. Review what each layout returns, because every page under it receives it.

A shared data access module (for example in a server-only directory) that takes the user from locals and enforces ownership in one place makes these checks consistent. The Next.js Server Actions and Data Access Layer Security Guide describes the same pattern for a different framework.

Form actions and remote functions

Form actions in +page.server are public HTTP endpoints. The documentation notes that actions always use POST, because GET requests should never have side effects, and that validation failures are returned with fail(), typically with status 400 or 422. The examples in the documentation leave login and registration as placeholders, so access control inside each action is entirely your responsibility.

For each action:

  1. Check locals.user and the user's right to perform this action on this object, at the top of the action.
  2. Parse and validate every field from request.formData() against a schema. Reject unexpected fields rather than ignoring them silently, and set size limits on file uploads.
  3. Return only safe values with fail(). The documentation's own example returns the email but not the password, as a precaution.
  4. Update event.locals if the action changes the session cookie.
  5. Do not wrap redirect() in a try block.

Progressive enhancement with use:enhance changes the client experience, not the server contract. The action must be safe when called directly with any payload.

Remote functions (query, form, command and related helpers) are where new SvelteKit development is focused. They are documented as experimental, with an API that may change. Each remote function is a server endpoint callable from the browser, so the same rules apply: validate arguments with a schema, authorise inside the function, and never use client-supplied values to decide authorisation. Several 2026 advisories (below) concerned remote function deserialisation and batching, which is a reason to keep their use behind a feature review until the API stabilises.

Content Security Policy

SvelteKit can generate a Content Security Policy for you through kit.csp in the configuration. Its key settings:

  • mode: 'hash', 'nonce' or 'auto'. The documentation explains that 'auto' uses hashes for prerendered pages and nonces for dynamically rendered pages, and that using nonces with prerendered pages is insecure and therefore forbidden.
  • directives: written into the Content-Security-Policy header. SvelteKit adds nonces or hashes for the inline scripts and styles it generates.
  • reportOnly: written into Content-Security-Policy-Report-Only, and must include report-uri or report-to.
  • Manual tags: scripts and links you add to src/app.html use the %sveltekit.nonce% placeholder.

Two limits are worth knowing. For prerendered pages the policy is delivered in a <meta http-equiv> tag, in which frame-ancestors, report-uri and sandbox are ignored, so set those as HTTP headers at your CDN or adapter. And where you need per-request logic, the documentation suggests building the header yourself in handle.

A sensible rollout is to start with reportOnly and mode: 'auto', collect reports for a release cycle, then enforce a policy based on script-src 'self' plus the generated hashes or nonces. Avoid 'unsafe-inline' for scripts. NHI Mgmt Group advice: treat interpolated text as escaped by Svelte but {@html ...} output as raw HTML, so treat every use of it as a sanitisation review item. The Content Security Policy Guide covers directive design in detail.

Secrets, environment variables and server-only code

SvelteKit enforces a build-time boundary between server and browser code. A module becomes server-only if its filename contains a .server segment (for example secrets.server.ts) or if it sits in a server directory such as src/lib/server. Private environment modules can only be imported into server-only code such as hooks.server or +page.server. If browser-bound code imports server-only code, directly or indirectly and including dynamic imports, SvelteKit throws an error, even when only a non-secret export is used.

The boundary has documented gaps:

  • Illegal import detection is disabled when running tests (process.env.TEST === 'true').
  • Modules outside the working directory and modules in node_modules are not subject to the rules. A package that handles secrets should add import '$app/server' at the top of the file to opt in.
  • The private environment module name and the location rules for server directories differ between major versions, so check the documentation for the version you run.

The boundary stops secrets reaching the bundle. It does not stop a server load returning a secret in its data, or an error message leaking a connection string. Those still need code review.

The credentials themselves (database passwords, API keys for payment and email providers, OAuth client secrets) are non-human identities owned by the app. Load them from a secrets manager or the platform's encrypted environment at deploy time, give each environment its own credentials, scope them to what the app needs, and rotate them. Public environment variables are visible to anyone, so never place an API key with write or admin rights in one.

Framework advisories in 2026 and patching

The SvelteKit repository's security advisories page listed the following moderate and low severity advisories published in 2026, at the time of writing:

PublishedAdvisoryArea
29 Jul 2026ReDoS in content negotiation header parsing (GHSA-29g2-3rmr-qm68)Core request handling
2 Jul 2026Large remote form function payloads can crash the Node process (GHSA-wqjv-9729-c5q2)Remote functions
2 Jul 2026Prototype pollution in file input deletion path in remote-function forms (GHSA-866w-xmhq-wj7x)Remote functions
14 May 2026query.batch cross-talk (GHSA-hgv7-v322-mmgr)Remote functions
9 Apr 2026Unvalidated redirect in handle hook causes denial of service (GHSA-3f6h-2hrp-w5wx)Hooks
9 Apr 2026BODY_SIZE_LIMIT bypass in adapter-node (GHSA-2crg-3p73-43xp)Adapter
26 Feb 2026Deserialisation expansion in unvalidated form remote function (GHSA-fpg4-jhqr-589c)Remote functions (experimental)
18 Feb 2026Memory and CPU exhaustion in remote form deserialisation (GHSA-vrhm-gvg7-fpcf, GHSA-88qp-p4qg-rqm6)Remote functions (experimental)
18 Feb 2026Cache poisoning in adapter-vercel (GHSA-9pq4-5hcf-288c)Adapter

Check each advisory for affected and patched versions. The pattern is the useful lesson: most 2026 issues sat in request parsing, newer experimental features and deployment adapters, not in application code. Patch @sveltejs/kit, the adapter you deploy with and svelte itself together, subscribe to the repository's advisories, and enforce request body limits at the proxy as well as in the adapter. The Software Composition Analysis (SCA) Guide covers automating this.

Common failure patterns

  • Layout-only authorisation. The admin layout checks the role, but a child page's server load fetches data concurrently and returns it anyway.
  • Returning whole database rows. A server load returns the user record including hash and internal flags, which then appear in the page's serialised data.
  • Disabling the origin check. checkOrigin: false or trustedOrigins: ['*'] is added to make a third-party form post work.
  • Swallowed redirects and errors. redirect() or error() inside a try block, so a denied request renders.
  • Unvalidated actions. Form actions and remote functions trust form field names and types and accept user IDs from the client.
  • Stale locals. Logout deletes the cookie in an action but leaves locals.user set for the following load.
  • Leaky error handler. handleError returns the raw error message to the client.
  • Secrets in public variables. A key is placed in a public environment variable because the browser code needed it.
  • Unpatched adapter. The framework is updated but the adapter package is pinned to an old version.

Practitioner checklist

  • The CSRF origin check is enabled, trustedOrigins lists only named, documented origins and never '*'.
  • handle resolves the session into event.locals; actions that change the session update locals.
  • Every server load, form action, endpoint and remote function authorises the specific object using locals, not request values.
  • Server load return values are explicit field mappings reviewed for sensitive data.
  • All action and remote function inputs are schema-validated with size limits.
  • No redirect() or error() calls sit inside try blocks.
  • handleError logs details server side and returns a generic message with an ID.
  • kit.csp is configured with mode: 'auto', piloted in report-only, and header-only directives are set at the CDN for prerendered pages.
  • Every {@html} use is reviewed and sanitised.
  • Secrets live in server-only modules and private environment variables loaded from a secrets manager, with per-environment credentials.
  • @sveltejs/kit, svelte and the adapter are patched together and repository advisories are monitored.

Standards and references

Related NHI Mgmt Group resources: React and Next.js Security Guide · CSRF Prevention Guide · Content Security Policy Guide · Cross-Site Scripting (XSS) Prevention Guide

PDF for subscribers

Take this guide with you

Every section, table and checklist in one PDF, with links to the sources and related guides. Subscribe to our weekly NHI & AI Identity Journal and we’ll email you a download link.

Free weekly newsletter

Subscribe to the NHI & AI Identity Journal

The latest on NHI and Agentic AI security – articles, research, breaches, news and events every week.

Bonus 33% off our NHI Course when you subscribe.

PDF Downloads for Newsletter Subscribers

Get the guide

Enter your details and we’ll email you a download link.

The full guide is free to read online. The PDF is a thank you for subscribing.

Fill in all fields marked * and tick both boxes to continue.