🖥 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 📼
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 #
🖥 SvelteKit Session Cookie: Code #
1 import cookie from 'cookie';2 const COOKIE_NAME = process.env['USER_COOKIE_NAME'];34 export async function getSession(request) {5 if (request.locals.user) {6 return { user: request.locals.user };7 }8 return {};9 }1011 export async function handle({ request, resolve }) {12 const loggingOut = request.path === '/api/logout.json';1314 const cookies = cookie.parse(request.headers.cookie || '');1516 // before endpoint call17 request.locals.user = cookies[COOKIE_NAME];1819 // endpoint call20 const response = await resolve(request);2122 // after endpoint call23 const user = loggingOut ? '' : request.locals.user;2425 const secure = process.env.NODE_ENV === 'production';26 const maxAge = 7_200; // (3600 seconds / hour) * 2 hours27 const sameSite = 'Strict';28 const setCookieValue = `${COOKIE_NAME}=${user || ''}; Max-Age=${maxAge}; Path=/; ${29 secure ? 'Secure;' : ''30 } HttpOnly; SameSite=${sameSite}`;3132 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.