summaryrefslogtreecommitdiff
path: root/src/lib/server/setcookie.ts
blob: f64b380bf047a8ffc255e2922db3ac6a6ae3be34 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import type { Middleware } from "waku/config";
import { type ResponseCookie, stringifyCookie } from "@edge-runtime/cookies";

export const mergeSetCookies = (
  resSetCookies: string | string[],
  cookiesInContext: ResponseCookie[],
) => {
  if (typeof resSetCookies === "string") {
    resSetCookies = [resSetCookies];
  }
  return [...resSetCookies, ...cookiesInContext.map(stringifyCookie)];
};

const setCookieMiddleware: Middleware = () => {
  return async (ctx, next) => {
    await next();
    ctx.res.headers ||= {};
    ctx.res.headers["set-cookie"] = mergeSetCookies(
      ctx.res.headers["set-cookie"] || [],
      (ctx.data.cookies || []) as ResponseCookie[],
    );
  };
};

export default setCookieMiddleware;