MAIS AMOR POR FAVOR

SvelteKit Session Cookies: going HttpOnly

SvelteKit Session Storage

SvelteKit Session Cookies: going HttpOnly

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.

SvelteKit Session Cookies

πŸ—³οΈ Poll

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

πŸ–₯ SvelteKit Session Cookie: Code

src/hooks.js
javascript
1import cookie from 'cookie';
2const COOKIE_NAME = process.env['USER_COOKIE_NAME'];
3
4export async function getSession(request) {
5 if (request.locals.user) {
6 return { user: request.locals.user };
7 }
8 return {};
9}
10
11export 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 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.