If you need to store a cookie in a form action, you can do so by setting it without the HttpOnly attribute (although this is not recommended due to potential security vulnerabilities).
Here's a straightforward example:
<!-- +page.svelte -->
<script lang="ts">
import { enhance } from '$app/forms';
export let form: { error?: string; } | null;
</script>
<form method="post" use:enhance>
<label>Login <input type="text" name="login" /></label>
<label>Password <input type="password" name="password" /></label>
{#if form?.error}<p>{form.error}</p>{/if}
<button type="submit">Login</button>
</form>
// +page.server.ts
import { fail, redirect } from '@sveltejs/kit';
import type { Actions } from './$types';
export const actions: Actions = {
default: async ({ request, cookies }) => {
const formData = await request.formData();
const login = formData.get('login');
const password = formData.get('password');
if (login == 'admin' && password == '...') {
cookies.set(
'auth', '42',
{
path: '/',
maxAge: 60 * 60 * 24 * 365,
httpOnly: false, // <-- if you want to read it in the browser
},
);
redirect(302, '/');
}
return fail(400, { error: 'Invalid login or password' });
},
}
To access the cookie, you can use document.cookie
, but keep in mind that this may cause errors during SSR. Make sure to check for browser
or read it in onMount
.