Opens an external site in a new window
Pray for peace.
RODNEY LAB
  • Home
  • Plus +
  • Projects
  • Giving
  • Contact
RODNEY LAB
  • Home
  • Plus +
  • Newsletter
  • Contact

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

SvelteKit Session Storage
  1. Rodney Lab Home
  2. Rodney Lab Blog Posts
  3. SvelteKit Blog Posts
<PREVIOUS POST
NEXT POST >
LATEST POST >>

SvelteKit Session Cookies: going HttpOnly #

Updated 9 months ago
4 minute read Gunning Fog Index: 5.8
Content by Rodney
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 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 #

I should point out a small error in the video. The maxAge for a cookie should be specified in seconds. This is corrected in the hooks.js code below.

Please enable JavaScript to watch the video 📼

SvelteKit Session Cookies

Note that SvelteKit layout resets have changed since recording this video. The GitHub repo is up-to-date and works on the layout API  . Only two files are affected: src/routes/dashboard/__layout.reset.svelte is now src/routes/__layout-dashboard.svelte and src/routes/dashboard/index.svelte is now src/routes/[email protected]. The content of the files remains the same, just the paths changed.

🗳 Poll #

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

🖥 SvelteKit Session Cookie: Code #

src/hooks.js
javascript
    
1 import cookie from 'cookie';
2 const COOKIE_NAME = process.env['USER_COOKIE_NAME'];
3
4 export async function getSession(request) {
5 if (request.locals.user) {
6 return { user: request.locals.user };
7 }
8 return {};
9 }
10
11 export async function handle({ request, resolve }) {
12 const loggingOut = request.path === '/api/logout.json';
13
14 const cookies = cookie.parse(request.headers.cookie || '');
15
16 // before endpoint call
17 request.locals.user = cookies[COOKIE_NAME];
18
19 // endpoint call
20 const response = await resolve(request);
21
22 // after endpoint call
23 const user = loggingOut ? '' : request.locals.user;
24
25 const secure = process.env.NODE_ENV === 'production';
26 const maxAge = 7_200; // (3600 seconds / hour) * 2 hours
27 const sameSite = 'Strict';
28 const setCookieValue = `${COOKIE_NAME}=${user || ''}; Max-Age=${maxAge}; Path=/; ${
29 secure ? 'Secure;' : ''
30 } HttpOnly; SameSite=${sameSite}`;
31
32 return {
33 ...response,
34 headers: {
35 ...response.headers,
36 ...(user || loggingOut ? { 'Set-Cookie': setCookieValue } : {})
37 }
38 };
39 }

🔗 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 docs  .

🏁 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 in a similar way 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, indentifying 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.

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 Optimisation 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 …

Rodney from Rodney Lab
TAGS:
SVELTEKIT

Related Posts

Astro Cookies API: Cookies on HTTP Requests 🍪

Astro Cookies API: Cookies on HTTP Requests 🍪

astro
<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 – 2023 Rodney Johnson. All Rights Reserved. Please read important copyright and intellectual property information.

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