What is the best way to generate a cookie in svelte and retrieve it later on?

I have been working on implementing a cookie in Svelte (while also using Svelte Kit) for the purpose of storing a JWT Token used in authentication processes. I initially tried using pure JavaScript code like getCookie() and setCookie(), following the guide provided by W3Schools - JavaScript Cookies. However, I encountered issues in accessing the document object. Additionally, I experimented with methods such as serializing from the npm package cookie and utilizing the browser environment as demonstrated below.

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

Answer №1

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.

Answer №2

If you want to include it in a script tag within a file, you must wait for the DOM to be loaded. This allows you to retrieve document.cookie within a function called by an element, or you can utilize the onMount lifecycle.

An example would look like this:

onMount(() => {
        document.cookie = "theme=light";
});

I realize this post is old, but I had some difficulty solving this issue myself. Hopefully, it can assist someone else as well.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The issue of memory leakage with ng-grid and real-time data

My intention is to utilize ng-grid for visualizing high-frequency real-time data, but I am encountering issues with a memory leak. Interestingly, the memory leak does not occur when I opt for a simple HTML table with ng-repeat. My tech stack includes node ...

The Node.js application gracefully exited with code 0 with Forever

Running a Node.js Express app on CentOs 6.5 using the root account: root@vps [/home/test/node]# npm start app.js > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="aedacbdddaee9e809e809f">[email protected]</a> s ...

Using Node.js to instantly redirect users to a new page while also sending them important

I am currently working on building a basic server for HTML pages using Node.js. The issue I am facing is that when I go to (for instance) http://localhost:8080/someDirectory, the browser mistakenly treats someDirectory as a file (when in reality, it is int ...

A JavaScript function that instantiates an object that invokes its own function

Currently, I am working on an Angular service that is meant to return a new object. Everything seems to be fine and in working order. When I use new MakeRoll(), it successfully creates an instance. However, the issue arises when I call self.add towards th ...

Sophisticated sinatra parameter

Creating Dynamic Surveys <script type="text/x-jsrender" id="surveyTemplate"> <li class="question"> <input type="text" name="survey[question]" /> <button class="add_answer">Add Answer</button> <ul> ...

express-validator, no validation errors have been found so far

How can I verify if a given string is in the format of an email address? Here's a snippet of code that attempts to do so: req.checkBody('email', 'Invalid email address').isEmail(); var validationErrors = req.validationErrors(); i ...

How to Pass Data as an Empty Array in Angular 6

After successfully implementing a search function that filters names from an array based on user input, I encountered an issue when trying to make the searchData dynamic by fetching it from a Firebase database: getArray(): void { this.afDatabase.list( ...

Encountering an error in TypeScript: Attempting to define type files for a third-party library triggers the TS2709 error when attempting to use the 'Optional' namespace as a type

Currently, I'm in the process of creating type files for a third-party library called optional-js. The structure is as follows: index.js var Optional = require('./lib/optional.js'); module.exports = { empty: function empty() { ...

What could be causing JavaScript fetch to only send OPTIONS requests instead of the expected calls?

I'm having an issue with my AJAX request using javascript fetch. It's only sending an OPTIONS call and not proceeding to make further calls. What's strange is that the response header seems fine, and $.ajax is working as expected. Check out ...

Tips for calculating the total sum of inner object property values using JavaScript, TypeScript, or Angular 5

What is the total sum of successCount values in the given array object? var successCount;//I want count of all successCount attributes from the below object var accordianData = [ { name: "Start of Day", subItemsData: [ { title: " ...

Adjust the menu scrollbar position to the right or limit scrolling to within the menu area

$(function() { "use strict"; $(".navbar-toggler").on("click", function() { $(".navbar-toggler").toggleClass("collapsed"); $(".offcanvas-collapse").toggleClass("open"); let menuposition = $("#toggler").offset().left + $("#toggler").width() + ...

What is the process to switch the div's contenteditable attribute value from "false" to "true"?

I am currently experimenting with angular2 and I have a need to alter the value of a div- I want to change all contenteditable="false" to contenteditable="true" on my HTML page. Note that at times the contenteditable="false" attribute may be added to a ...

Beginner's guide to using Express: a step-by-step tutorial on making API requests from client-side JavaScript to

Currently, I am immersed in a Javascript project where I utilize the Nasa Mars Rover API and Immutable Js to creatively display images and information on my webpage. By harnessing the power of pure functions and functional programming, I maintain app state ...

A guide on sending a post request with Axios to a parameterized route in Express

Recently, I set up an express route router.post('/:make&:model&:year', function (req, res) {   const newCar = {     make: req.params.make,     model: req.params.model,     year: req.params.year   }   Car.create(newCar);   res ...

How about utilizing React's conditional rendering feature?

I'm currently working on a component that displays tournaments and matches, and I'm facing a challenge in implementing a filter option for users to select tournaments by 'league', while still displaying all tournaments if no 'leagu ...

Importing cookies directly into server actions in Next JS 13 is not possible for me

Currently, I am tackling a project using Next JS 13 and came across an issue pertaining to server actions. While server actions can be directly applied on form or button components, my personal preference is to define server components in separate files an ...

What is the best way to consistently resize elements to the same pixel value, like "10px", using jquery-ui?

Is there a method to consistently resize a div element by a specific pixel value each time, such as "10px"? I am attempting to achieve this using jquery-ui, where I can resize the element but desire to resize it consistently by a set pixel value. $(child ...

My Gatsby website is being rendered in its HTML form on Netlify

The website build is located at . It appears that the javascript functionality is not working, and only the html version (usually meant for search engines) is being displayed. It seems like this issue is only affecting the home page. You can check out the ...

How can I trigger the rendering of a component by clicking a button in a separate component?

I am currently facing a challenge in rendering a component with an "Edit" button that is nested within the component. I attempted to use conditional rendering in my code, but unfortunately, I am struggling to make it work as expected. Does anyone have any ...

Event to discard currently selected pushpin in Bing Maps v8

There are two event styles available for a pushpin in Bing. enableHoverStyle : Boolean enableClickedStyle : Boolean To see these events/styles in action, visit the link below: My goal is to deselect an already selected pin when another pin is selected. ...