Opens an external site in a new window
Mental Health Awareness Month
“Community”
RODNEY LAB
  • Home
  • Plus +
  • Newsletter
  • Links
  • Profile
RODNEY LAB
  • Home
  • Plus +
  • Newsletter
  • Links

SvelteKit Session Cookies: going HttpOnly # SvelteKit Session Cookies: going HttpOnly #

blurry low resolution placeholder image SvelteKit Session Storage
  1. Home Rodney Lab Home
  2. Blog Posts Rodney Lab Blog Posts
  3. SvelteKit SvelteKit Blog Posts
<PREVIOUS POST
NEXT POST >
LATEST POST >>

SvelteKit Session Cookies: going HttpOnly #

Published: 2 years ago
3 minute read
Gunning Fog Index: 5.8
Content by Rodney
blurry low resolution placeholder image Author Image: Rodney from Rodney Lab
SHARE:

🖥 SvelteKit Session Cookies: HttpOnly Cookies in SvelteKit #

In this video, we look at using SvelteKit Session Cookies, continuing the series of videos which also covers Session Storage and Local Storage. We focus particularly on HttpOnly cookies which can be more secure than other cookies. That is because JavaScript code running in the browser has no access to them. The main benefit here is a decreased attack surface for Cross Site Scripting (XSS) attacks. In the video, we see how you might consider setting up a SvelteKit app where you need users to authenticate. We also see how you can expose client-safe fields stored in cookies to browser JavaScript using SvelteKit sessions.

If that sounds like something you can use, let's press play and crack on!

📹 SvelteKit Session Cookie: Video #

Please enable JavaScript to watch the video 📼

SvelteKit Session Cookies

🗳 Poll #

What’s your most loved browser data method?
Voting reveals latest results.

🖥 SvelteKit Session Cookie: Code Examples #

Clone the repo and play around a little to get a better feel for how it works. Link below.

Checking HTTPOnly Cookie for a User Session #

src/routes/console/+server.ts
typescript
    
1 import { redirect } from '@sveltejs/kit';
2 import type { LayoutServerLoad } from './$types';
3
4 export const load: LayoutServerLoad = async function load({ cookies }) {
5 const session = cookies.get('session');
6
7 if (!session) {
8 throw redirect(303, '/login');
9 }
10
11 const { email } = JSON.parse(session);
12 if (!email) {
13 throw redirect(303, '/login');
14 }
15
16 return {};
17 };

Create Cookie Utility Function #

src/lib/session.ts
typescript
    
1 import { Temporal } from '@js-temporal/polyfill';
2 import type { Cookies } from '@sveltejs/kit';
3
4 export function createSession(cookies: Cookies) {
5 const sessionID = crypto.randomUUID();
6 cookies.set('session', JSON.stringify({ sessionID }), {
7 path: '/',
8 expires: new Date(Temporal.Now.plainDateTimeISO().add({ hours: 2 }).toString()),
9 sameSite: 'lax',
10 httpOnly: true
11 });
12 }

Logging Out: Deleting the HTTPOnly Cookie #

src/routes/console/logout/+page.server.ts
typescript
    
1 import { redirect } from '@sveltejs/kit';
2 import type { Actions } from './$types';
3
4 export const actions: Actions = {
5 logout: ({ cookies }) => {
6 const session = cookies.get('session');
7 if (session) {
8 cookies.delete('session', { path: '/' });
9 }
10 throw redirect(303, '/');
11 }
12 };

🔗 SvelteKit Session Storage: Links #

  • Using Local storage with SvelteKit
  • Using Session storage with SvelteKit,
  • Open full demo code repo on GitHub 
  • MDN Set-Cookie docs ,
  • OWASP HttpOnly information .

🏁 SvelteKit Session Cookies: Summary #

What is an HttpOnly Cookie? #

Http only cookies, unlike Session Storage and Local Storage cannot be read by JavaScript code running in the browser. This brings security benefits, making HttpOnly cookies a preferred choice in many applications.

How can you share data between the client and server in SvelteKit? #

SvelteKit has a session store. Client routes can access it via a named import from $app/stores. Once imported, it can be read similarly to other stores. Session is not suitable for storing sensitive information.

How can sensitive information be sent from the server to the client in SvelteKit? #

You can use HttpOnly cookies to send sensitive information, identifying a user or session, as well as session tokens. The client can send this data to the server with client requests, to process the sensitive data and respond with client-safe data. The server can access the data on the cookie, but client side JavaScript code cannot.

🙏🏽 Feedback #

If you have found this video useful, see links below for further related content on this site. I do hope you learned one new thing from the video. Let me know if there are any ways I can improve on it. I hope you will use the code or starter in your own projects. Be sure to share your work on Twitter, giving me a mention, so I can see what you did. Finally, be sure to let me know ideas for other short videos you would like to see. Read on to find ways to get in touch, further below. If you have found this post useful, even though you can only afford even a tiny contribution, please consider supporting me through Buy me a Coffee.

blurry low resolution placeholder image ask Rodney X (formerly Twitter) avatar

Rodney

@askRodney

Just updated the video on using HTTP only session 🍪cookies in SvelteKit.

We see a couple of traps to avoid, using a skeleton app, where users need an account to see their console. Full code on GitHub.

Hope you find it useful!

#learnsvelte #askRodneyhttps://t.co/A7Xwj8f1ox

— Rodney (@askRodney) June 30, 2023

Finally, feel free to share the post on your social media accounts for all your followers who will find it useful. As well as leaving a comment below, you can get in touch via @askRodney on Twitter and also askRodney on Telegram . Also, see further ways to get in touch with Rodney Lab. I post regularly on SvelteKit as well as Search Engine Optimization among other topics. Also, subscribe to the newsletter to keep up-to-date with our latest projects.

Thanks for reading this post. I hope you found it valuable. Please get in touch with your feedback and suggestions for posts you would like to see. Read more about me …

blurry low resolution placeholder image Rodney from Rodney Lab
TAGS:
SVELTEKIT

Related Posts

blurry low resolution placeholder image Svelte Login Form Example: Best Practices ✅

Svelte Login Form Example: Best Practices ✅

sveltekit
<PREVIOUS POST
NEXT POST >
LATEST POST >>

Leave a comment …

Your information will be handled in line with our Privacy Policy .

Ask for more

1 Nov 2022 — Astro Server-Side Rendering: Edge Search Site
3 Oct 2022 — Svelte eCommerce Site: SvelteKit Snipcart Storefront
1 Sept 2022 — Get Started with SvelteKit Headless WordPress

Copyright © 2020 – 2025 Rodney Johnson. All Rights Reserved. Please read important copyright and intellectual property information.

  • Home
  • Profile
  • Plus +
  • Newsletter
  • Contact
  • Links
  • Terms of Use
  • Privacy Policy
We use cookies  to enhance visitors’ experience. Please click the “Options” button to make your choice.  Learn more here.