Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: cookies managment #1855

Closed
Lastknight12 opened this issue Apr 27, 2024 · 0 comments
Closed

feat: cookies managment #1855

Lastknight12 opened this issue Apr 27, 2024 · 0 comments
Labels
🌟 enhancement New feature or request

Comments

@Lastknight12
Copy link

Is your feature request related to a problem? Please describe.

the t3 stack does not provide for cookie management

Describe the solution you'd like to see

/api/trpc/[trpc]:

in createTRPCContext we can pass resHeaders which displays the response headers as well as the request

const handler = (req: NextRequest) => {
  req.headers.set("asdsd", "asdasdas")
  return fetchRequestHandler({
    endpoint: "/api/trpc",
    req,
    router: appRouter,
    createContext: ({ resHeaders }) => createTRPCContext({ req, resHeaders }), <======================
    onError:
      env.NODE_ENV === "development"
        ? ({ path, error }) => {
            console.error(
              `❌ tRPC failed on ${path ?? "<no-path>"}: ${error.message}`
            );
          }
        : undefined,

  });
}

/server/api/trpc.ts:

here we use req and resHeaders to get and create a cookie and then return

type CreateContextOption = {
  reqHeaders: Headers | undefined
  resHeaders: Headers
}

export const createTRPCContext = async (opts: {
  req?: NextRequest
  resHeaders: Headers
}) => {
  return await createInnerTRPCContext({
    reqHeaders: opts.req?.headers,
    resHeaders: opts.resHeaders,
  })
}

export const createInnerTRPCContext = async (opts: CreateContextOption) => {
  const serverAuthSession = await getServerAuthSession()
  const cookies = {
    get: (name?: string) => {

      const cookiesHeader = opts.reqHeaders?.get('Cookie') <=============
      if (!cookiesHeader) return null
      const cookies = parse(cookiesHeader)
      return name ? cookies[name] ?? null : cookies
    },
    has: (name: string) => {
      const cookiesHeader = opts.reqHeaders?.get('Cookie') <==============
      if (!cookiesHeader) return false
      const cookies = parse(cookiesHeader)
      return name in cookies
    },
    set: (name: string, value: string, options?: CookieSerializeOptions) => {
      opts.resHeaders.append('Set-Cookie', serialize(name, value, options)) <===============
    },
    clear: (name: string) => {
      opts.resHeaders.append('Set-Cookie', serialize(name, '', { maxAge: -1 })) <==============
    },
  }

  return {
    session: serverAuthSession,
    headers: opts.reqHeaders,
    cookies: cookies, <=============
  }
}

and now we can work with cookies in our procedures

/server/api/routers/post.ts

create: protectedProcedure
    .input(z.object({ name: z.string().min(1) }))
    .mutation(async ({ input, ctx }) => {
      // simulate a slow db call
      const expiresDate = new Date();
      expiresDate.setDate(expiresDate.getDate() + 2);

      ctx.cookies.set("cookie_name", "cookie_value", {  <=============
          expires: expiresDate,
          path: '/',
      });

      post = { id: post.id + 1, name: input.name };
      return post;
    }),

Describe alternate solutions

not found

Additional information

we can also now pass resHeaders to our context and, for example, create some headers

@Lastknight12 Lastknight12 added the 🌟 enhancement New feature or request label Apr 27, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
🌟 enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

1 participant