Files
family_wishlist/apps/backend/src/plugins/guest.ts

26 lines
730 B
TypeScript

import fp from 'fastify-plugin';
import { nanoid } from 'nanoid';
import { env } from '../config/env.js';
export const GUEST_COOKIE = 'fw_gid';
const GUEST_COOKIE_MAX_AGE = 60 * 60 * 24 * 365 * 2; // 2 years
export default fp(async (app) => {
app.addHook('onRequest', async (request, reply) => {
const existing = request.cookies[GUEST_COOKIE];
if (existing && existing.length >= 16 && existing.length <= 64) {
request.guestId = existing;
return;
}
const id = nanoid(24);
request.guestId = id;
reply.setCookie(GUEST_COOKIE, id, {
httpOnly: true,
secure: env.NODE_ENV === 'production',
sameSite: 'lax',
path: '/',
maxAge: GUEST_COOKIE_MAX_AGE,
});
});
});