Home > Blockchain >  Cookies are not getting set when running with --host option in official SvelteKit example
Cookies are not getting set when running with --host option in official SvelteKit example

Time:01-08

I am trying offical SvelteKit example https://realworld.svelte.dev/.
Its code is hosted at https://github.com/sveltejs/realworld

login and everything works fine when I run npm run dev but when I run npm run dev -- --host then login does not work.

cookies.set('jwt', value, { path: '/' });

This is not working so cookies are not getting set so login is not working.

How can I make login working when using --host option?

CodePudding user response:

I'm assuming you're blocked from logging in when addressing the exposed network IP URL (localhost should still work) on an unsecured (http) connexion.

The reason for this is because the default cookie configuration in SvelteKit is to set the secure option to true, meaning cookies won't get set upon unsecured requests. From the SvelteKit docs:

The httpOnly and secure options are true by default (except on http://localhost, where secure is false), and must be explicitly disabled if you want cookies to be readable by client-side JavaScript and/or transmitted over HTTP. The sameSite option defaults to lax.

As you can see, this explains why the default configuration works on localhost (where secure is false) but not on the exposed network IP address (where secure will be true).

If you update the cookie configuration in src/routes/login/ page.server.js to explicitly set the secure option:

cookies.set('jwt', value, { secure: false, path: '/' });

and restart your server, you should then be able to login as expected from the exposed network IP URL (I was able to).

Note: in a production deployment, you will want the secure flag set to true and use a secure protocol (https) for your requests.

  • Related