Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I create a cookie in svelte and access it?

I am trying to create a cookie in svelte (and I am also using svelte kit) and access it. I am want to use the cookie for authentication purposes, more specifically, to store a JWT Token.

I am tried implementing pure JS code, such as getCookie() and setCookie() as shown here W3Schools – JavaScript Cookies. But I can’t get access to the document. I have also tried serialize from the cookie npm package, as shown below, and I have also tried using browser as shown below.

import { serialize } from "cookie";
import { browser } from '$app/environment';

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can e.g. set a cookie in a form action. If you want to be able to read it in the browser, you have to disable HttpOnly (in general you should avoid this, as it makes cross site scripting vulnerabilities worse).

A simple 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 { invalid, 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
                },
            );
            throw redirect(302, '/');
        }
        return invalid(400, { error: 'Invalid login or password' });
    },
}

The cookie can be read from document.cookie, note that this will throw an error during SSR, so you have to check browser or read it in onMount.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading