boredgame/src/hooks.server..ts

24 lines
668 B
TypeScript
Raw Normal View History

2022-01-28 05:27:12 +00:00
import type { Handle } from '@sveltejs/kit';
2022-08-29 17:17:32 +00:00
import * as cookie from 'cookie';
2022-01-28 05:27:12 +00:00
export const handle: Handle = async ({ event, resolve }) => {
const cookies = cookie.parse(event.request.headers.get('cookie') || '');
2022-08-29 17:17:32 +00:00
event.locals.userid = cookies['userid'] || crypto.randomUUID();
2022-01-28 05:27:12 +00:00
const response = await resolve(event);
2022-01-28 05:27:12 +00:00
2022-08-29 17:17:32 +00:00
if (!cookies['userid']) {
// if this is the first time the user has visited this app,
2022-08-29 17:17:32 +00:00
// set a cookie so that we recognise them when they return
response.headers.set(
'set-cookie',
cookie.serialize('userid', event.locals.userid, {
path: '/',
httpOnly: true
})
);
}
2022-01-28 05:27:12 +00:00
return response;
2022-01-28 05:27:12 +00:00
};