tRPCttRPC
Powered by
ivanI
tRPC•6mo ago•
3 replies
ivan

Set cookie header in procedure middleware

Hi,

I am trying to set the cookie header in my middleware "protected route" eg. whenever I decide user shouldn't be authorized anymore I would like to clear the cookie by setting
set-cookie
set-cookie
with max-age 0.

export function createContext({
  req,
  resHeaders,
}: FetchCreateContextFnOptions) {
  // custom code for parsing session - not important
  const userId = getUserId(req.headers);

  // see addSetCookie below
  const newHeaders = addSetCookies({
    // whenever I tried to pass `resHeaders` directly, I got error from client that it is unable to parse response - there was no error thrown in my code though
    headers: new Headers(resHeaders),
    sid: toSid(userId),
    maxAge: 3600
  });

  return {
    req,
    resHeaders: newHeaders,
    userId,
  };
}

function addSetCookies(props: {
  headers: Headers;
  sid: string;
  maxAge: number;
}): Headers {
  [
    `__Host-SID=${props.sid}; HttpOnly; Max-Age=${props.maxAge}; SameSite=Strict; Secure; Path=/`,
    `aSID=${props.maxAge > 0 ? 1 : 0}; Max-Age=${props.maxAge}; SameSite=Strict; Secure; Path=/`,
  ].forEach((value) => props.headers.append("Set-Cookie", value));

  return props.headers;
}
export function createContext({
  req,
  resHeaders,
}: FetchCreateContextFnOptions) {
  // custom code for parsing session - not important
  const userId = getUserId(req.headers);

  // see addSetCookie below
  const newHeaders = addSetCookies({
    // whenever I tried to pass `resHeaders` directly, I got error from client that it is unable to parse response - there was no error thrown in my code though
    headers: new Headers(resHeaders),
    sid: toSid(userId),
    maxAge: 3600
  });

  return {
    req,
    resHeaders: newHeaders,
    userId,
  };
}

function addSetCookies(props: {
  headers: Headers;
  sid: string;
  maxAge: number;
}): Headers {
  [
    `__Host-SID=${props.sid}; HttpOnly; Max-Age=${props.maxAge}; SameSite=Strict; Secure; Path=/`,
    `aSID=${props.maxAge > 0 ? 1 : 0}; Max-Age=${props.maxAge}; SameSite=Strict; Secure; Path=/`,
  ].forEach((value) => props.headers.append("Set-Cookie", value));

  return props.headers;
}


My
protectedProcedure
protectedProcedure
looks like this:

const protectedProcedure = t.procedure.use(async ({ ctx, next }) => {
  if (ctx.userId == null) {
    // not sure if throw here is the best option, but I tried to return 200OK as you can see below as well
    throw new TRPCError({ code: "UNAUTHORIZED" });

    // return {
    //   ok: true,
    //   data: null,
    //   marker: "middlewareMarker" as "middlewareMarker" & {
    //     __brand: "middlewareMarker";
    //   },
    // };
  }

  return next({
    ctx: {
      userId: ctx.userId,
    },
  });
});
const protectedProcedure = t.procedure.use(async ({ ctx, next }) => {
  if (ctx.userId == null) {
    // not sure if throw here is the best option, but I tried to return 200OK as you can see below as well
    throw new TRPCError({ code: "UNAUTHORIZED" });

    // return {
    //   ok: true,
    //   data: null,
    //   marker: "middlewareMarker" as "middlewareMarker" & {
    //     __brand: "middlewareMarker";
    //   },
    // };
  }

  return next({
    ctx: {
      userId: ctx.userId,
    },
  });
});


Is there anything I should be doing differently? Thanks in advance for any help.
Solution
It seems, that everything works as expected.

The problem was with the Bun lambda runtime where it didn't correctly returned cookies which caused 502 error. The fix is already in pull request here https://github.com/oven-sh/bun/pull/21018
GitHub
fix(bun-lambda): Resolve 502 error when setting cookies with HTTP A...
What does this PR do?
This PR fixes an issue in the bun-lambda package(noted in this issue #20760 ), specifically within the runtime.ts where responses containing cookies would cause a 502 Bad Gate...
fix(bun-lambda): Resolve 502 error when setting cookies with HTTP A...
Jump to solution
tRPCJoin
Move Fast & Break Nothing. End-to-end typesafe APIs made easy.
5,015Members
Resources
Recent Announcements

Similar Threads

Was this page helpful?

Similar Threads

Setting cookie via procedure
Answer OverflowAAnswer Overflow / ❓-help
2y ago
cookies not being set in procedure
propPprop / ❓-help
3y ago
Infer context from procedure after middleware
VinnieVVinnie / ❓-help
2y ago