Home > front end >  How do I create a cookie in svelte and access it?
How do I create a cookie in svelte and access it?

Time:10-31

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';

CodePudding user response:

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.

  • Related