Cursor rules for SvelteKit 2 with Svelte 5: typed load functions, form actions with validation, JSON endpoints, cookies and per-request user data.
.cursor/rules/sveltekit-full-stack-development.mdc. Downloaded files need to be placed in that repository path.---
description: "Cursor rules for SvelteKit 2 with Svelte 5: typed load functions, form actions with validation, JSON endpoints, cookies and per-request user data."
globs: "**/*"
alwaysApply: false
---
Apply these rules to SvelteKit 2 applications using Svelte 5.
## Project structure
```
src/
├── lib/
│ ├── components/ # reusable components
│ ├── server/ # server-only code (db, auth)
│ └── utils.ts
├── routes/
│ ├── +layout.svelte
│ ├── +layout.server.ts # exposes locals.user to every page
│ ├── +page.svelte
│ ├── posts/[id]/
│ │ ├── +page.svelte
│ │ └── +page.server.ts
│ └── api/posts/+server.ts
├── hooks.server.ts # reads the session cookie, sets event.locals.user
├── app.html
└── app.d.ts
```
## Page with a load function
```svelte
<!-- src/routes/posts/[id]/+page.svelte -->
<script lang="ts">
import type { PageProps } from './$types';
let { data }: PageProps = $props();
</script>
<article>
<h1>{data.post.title}</h1>
<p>{data.post.content}</p>
</article>
```
```ts
// src/routes/posts/[id]/+page.server.ts
import { error } from '@sveltejs/kit';
import type { PageServerLoad } from './$types';
import { db } from '$lib/server/db';
export const load: PageServerLoad = async ({ params }) => {
const post = await db.post.findUnique({ where: { id: params.id } });
if (!post) error(404, 'Post not found');
return { post };
};
```
In SvelteKit 2, `error()` and `redirect()` throw for you; calling them is enough. Do not call them inside a `try` block that would catch them.
## Form actions
```svelte
<!-- src/routes/login/+page.svelte -->
<script lang="ts">
import { enhance } from '$app/forms';
import type { PageProps } from './$types';
let { form }: PageProps = $props();
</script>
<form method="POST" use:enhance>
<label>Email <input name="email" type="email" required value={form?.email ?? ''} /></label>
<label>Password <input name="password" type="password" required /></label>
{#if form?.error}<p class="error" role="alert">{form.error}</p>{/if}
<button type="submit">Log in</button>
</form>
```
```ts
// src/routes/login/+page.server.ts
import { fail, redirect } from '@sveltejs/kit';
import type { Actions } from './$types';
import { auth } from '$lib/server/auth';
export const actions = {
default: async ({ request, cookies }) => {
const data = await request.formData();
const email = data.get('email');
const password = data.get('password');
if (typeof email !== 'string' || typeof password !== 'string' || !email || !password) {
return fail(400, { email: typeof email === 'string' ? email : '', error: 'Email and password are required' });
}
const session = await auth.login(email, password);
if (!session) return fail(401, { email, error: 'Invalid credentials' });
cookies.set('session', session.id, { path: '/', httpOnly: true, sameSite: 'lax', secure: true });
redirect(303, '/dashboard');
},
} satisfies Actions;
```
- Return the user's non-secret input with `fail()` so the form can be re-filled; never return the password.
- In SvelteKit 2, `cookies.set` requires `path`.
## JSON endpoints
```ts
// src/routes/api/posts/+server.ts
import { error, json } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import { db } from '$lib/server/db';
export const GET: RequestHandler = async ({ url }) => {
const page = Math.max(1, Number(url.searchParams.get('page') ?? '1') || 1);
const posts = await db.post.findMany({ skip: (page - 1) * 10, take: 10 });
return json(posts);
};
export const POST: RequestHandler = async ({ request, locals }) => {
if (!locals.user) error(401, 'Unauthorized');
const body = await request.json();
if (typeof body?.title !== 'string' || typeof body?.content !== 'string') error(400, 'title and content are required');
const post = await db.post.create({
data: { title: body.title, content: body.content, authorId: locals.user.id },
});
return json(post, { status: 201 });
};
```
- Build database inputs from validated fields; never spread the request body into a create/update call.
## User and shared state
- Resolve the session in `hooks.server.ts`, set `event.locals.user`, and return the public user fields from `+layout.server.ts`. Components read it from `data` or `page.data` (`$app/state`).
- Do not keep per-user data in module-level stores or `$state`: on the server those modules are shared across requests. Use `.svelte.ts` modules or stores only for client-side UI state.
Cursor rules for Next.js 14+ App Router projects updated for Next.js 16 with async params, validated Route Handlers, generateMetadata and proxy.ts in place of middleware.
Cursor rules for strict TypeScript: compiler checks beyond strict, interfaces vs type aliases, real type guards, discriminated unions, utility types and branded IDs.
Cursor rules for Tailwind CSS v4: automatic class sorting, mobile-first breakpoints, CVA variants with merging, class-based dark mode via @custom-variant, and CSS-first @theme configuration.
Cursor
fullstack
Illustrative input and expected result. This example is a verification guide, not a recorded model run.
Content reviewed .
A SvelteKit 2 + Svelte 5 blog uses export let data, throw error(...), stores the session user in a module-level writable and spreads request bodies into db.post.create.
Apply the SvelteKit Full-Stack Development rule to src/routes/posts/[id], src/routes/login and src/routes/api/posts.
Pages use $props() with PageProps; load and actions call error()/redirect() without throw; the login action validates FormData types, returns fail() with the email but not the password, sets an httpOnly cookie with path; the POST endpoint builds the create input from validated fields and uses locals.user set in hooks.server.ts; the module-level user store is removed.
Cursor applies project rules stored as .mdc files in .cursor/rules. Each rule's frontmatter (description, globs, alwaysApply) decides whether it is always included, attached to matching files, chosen by the agent from its description, or only used when you @-mention it. Cursor also reads AGENTS.md in the project root and subdirectories for plain-Markdown instructions.
.cursor/rules/sveltekit-full-stack-development.mdcStarting point, not a tested configuration for your repository. Attached when files matching the globs are in context (alwaysApply: false with globs). Review the instructions, adapt the file paths and run your project's existing checks.
---
description: "SvelteKit Full-Stack Development project conventions"
globs: "**/*"
alwaysApply: false
---
Apply these rules to SvelteKit 2 applications using Svelte 5.
## Project structure
```
src/
├── lib/
│ ├── components/ # reusable components
│ ├── server/ # server-only code (db, auth)
│ └── utils.ts
├── routes/
│ ├── +layout.svelte
│ ├── +layout.server.ts # exposes locals.user to every page
│ ├── +page.svelte
│ ├── posts/[id]/
│ │ ├── +page.svelte
│ │ └── +page.server.ts
│ └── api/posts/+server.ts
├── hooks.server.ts # reads the session cookie, sets event.locals.user
├── app.html
└── app.d.ts
```
## Page with a load function
```svelte
<!-- src/routes/posts/[id]/+page.svelte -->
<script lang="ts">
import type { PageProps } from './$types';
let { data }: PageProps = $props();
</script>
<article>
<h1>{data.post.title}</h1>
<p>{data.post.content}</p>
</article>
```
```ts
// src/routes/posts/[id]/+page.server.ts
import { error } from '@sveltejs/kit';
import type { PageServerLoad } from './$types';
import { db } from '$lib/server/db';
export const load: PageServerLoad = async ({ params }) => {
const post = await db.post.findUnique({ where: { id: params.id } });
if (!post) error(404, 'Post not found');
return { post };
};
```
In SvelteKit 2, `error()` and `redirect()` throw for you; calling them is enough. Do not call them inside a `try` block that would catch them.
## Form actions
```svelte
<!-- src/routes/login/+page.svelte -->
<script lang="ts">
import { enhance } from '$app/forms';
import type { PageProps } from './$types';
let { form }: PageProps = $props();
</script>
<form method="POST" use:enhance>
<label>Email <input name="email" type="email" required value={form?.email ?? ''} /></label>
<label>Password <input name="password" type="password" required /></label>
{#if form?.error}<p class="error" role="alert">{form.error}</p>{/if}
<button type="submit">Log in</button>
</form>
```
```ts
// src/routes/login/+page.server.ts
import { fail, redirect } from '@sveltejs/kit';
import type { Actions } from './$types';
import { auth } from '$lib/server/auth';
export const actions = {
default: async ({ request, cookies }) => {
const data = await request.formData();
const email = data.get('email');
const password = data.get('password');
if (typeof email !== 'string' || typeof password !== 'string' || !email || !password) {
return fail(400, { email: typeof email === 'string' ? email : '', error: 'Email and password are required' });
}
const session = await auth.login(email, password);
if (!session) return fail(401, { email, error: 'Invalid credentials' });
cookies.set('session', session.id, { path: '/', httpOnly: true, sameSite: 'lax', secure: true });
redirect(303, '/dashboard');
},
} satisfies Actions;
```
- Return the user's non-secret input with `fail()` so the form can be re-filled; never return the password.
- In SvelteKit 2, `cookies.set` requires `path`.
## JSON endpoints
```ts
// src/routes/api/posts/+server.ts
import { error, json } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import { db } from '$lib/server/db';
export const GET: RequestHandler = async ({ url }) => {
const page = Math.max(1, Number(url.searchParams.get('page') ?? '1') || 1);
const posts = await db.post.findMany({ skip: (page - 1) * 10, take: 10 });
return json(posts);
};
export const POST: RequestHandler = async ({ request, locals }) => {
if (!locals.user) error(401, 'Unauthorized');
const body = await request.json();
if (typeof body?.title !== 'string' || typeof body?.content !== 'string') error(400, 'title and content are required');
const post = await db.post.create({
data: { title: body.title, content: body.content, authorId: locals.user.id },
});
return json(post, { status: 201 });
};
```
- Build database inputs from validated fields; never spread the request body into a create/update call.
## User and shared state
- Resolve the session in `hooks.server.ts`, set `event.locals.user`, and return the public user fields from `+layout.server.ts`. Components read it from `data` or `page.data` (`$app/state`).
- Do not keep per-user data in module-level stores or `$state`: on the server those modules are shared across requests. Use `.svelte.ts` modules or stores only for client-side UI state.
Ask for a small change to one matching file. Check the tool's loaded context or instruction view, inspect the diff for the requested convention, and run the relevant build or test. A well-formatted file does not guarantee the model follows every instruction.
Cursor's docs recommend keeping individual rules under 500 lines and splitting large rules into composable ones. Cursor's documentation states that it supports AGENTS.md in the project root and in subdirectories. Use AGENTS.md for plain-Markdown instructions you also want other tools to read, and .mdc rules when you need Cursor's scoping options (globs, description-based selection, always-apply).
Documentation checked 2026-11-05: Cursor docs: Rules
Cursor rules for Next.js 14+ App Router projects updated for Next.js 16 with async params, validated Route Handlers, generateMetadata and proxy.ts in place of middleware.
Cursor rules for strict TypeScript: compiler checks beyond strict, interfaces vs type aliases, real type guards, discriminated unions, utility types and branded IDs.
Cursor rules for Tailwind CSS v4: automatic class sorting, mobile-first breakpoints, CVA variants with merging, class-based dark mode via @custom-variant, and CSS-first @theme configuration.