Is there a way to properly type cookies #6716
Answered
by
theetherGit
kesdigital
asked this question in
Q&A
-
My current implementation is this,// types.d.ts
type Theme = 'dark' | 'light' | 'system';
/**
* CookieFactory - no pun intended
* @param fixedProps contains all extra types to be added to the default cookie type
* @param dynamicProps the default cookie type
* @returns
*/
function CookieFactory(fixedProps: { theme?: Theme }, dynamicProps: Record<string, string>) {
return Object.assign({}, dynamicProps, fixedProps);
}
type ExtendedCookies = ReturnType<typeof CookieFactory>;
// I got the CookieFactory code from StackOverflow and have no idea how it works since am new to typescript export let handle: Handle = async ({ event, resolve }) => {
const reqCookies: ExtendedCookies = cookie.parse(event.request.headers.get('Cookie') || '');
if (reqCookies.theme) {
event.locals.theme = reqCookies.theme;
} else {
event.locals.theme = defaultTheme;
}
/ .......
return response;
}; Any help will be greatly appreciated |
Beta Was this translation helpful? Give feedback.
Answered by
theetherGit
Sep 10, 2022
Replies: 2 comments 5 replies
-
Have you tried new cookie implementation of kit?? |
Beta Was this translation helpful? Give feedback.
3 replies
Answer selected by
kesdigital
-
// types
import type { LayoutServerLoad } from './$types';
export let load: LayoutServerLoad = ({ cookies }) => {
let theme: Theme = 'system';
const cookieTheme = cookies.get('theme');
if (cookieTheme) {
theme = cookieTheme as Theme;
} else {
cookies.set('theme', 'system', { secure: false, httpOnly: false })
}
return {theme}
} There is an alternative to this one where you are handling themes using cookie like you can use stores for themes which is more preferable (according to me). |
Beta Was this translation helpful? Give feedback.
2 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Have you tried new cookie implementation of kit??