tRPCttRPC
Powered by
IceAge2OnDVDI
tRPC•3y ago•
18 replies
IceAge2OnDVD

Next cookies() not being set on Mutation in App Dir (T3 Turbo)

Trying to set cookies inside TRPC using Nextjs App Router, using the T3 Turbo setup.

Setting cookies works fine inside Queries, but cookies are not set inside Mutations. Maybe I'm doing something wrong, not very up to date with TRPC + App Dir, or it could be a bug in next, not sure.

export const postRouter = createTRPCRouter({
  all: publicProcedure.query(({ ctx }) => {
    cookies().set("Cookies work on QUERY", "yes")
    return [{id:0,
      title: "query test",
      content: "a test for trpc query",
      createdAt: Date.now(),
      updatedAt: Date.now()}]
  }),

  create: publicProcedure
    .input(
      z.object({
        title: z.string().min(1),
        content: z.string().min(1),
      }),
    )
    .mutation(({ ctx, input }) => {
      cookies().set("Cookies work on MUTATION", "No!")
      console.log(cookies().getAll())
      return 200;
    }),
});
export const postRouter = createTRPCRouter({
  all: publicProcedure.query(({ ctx }) => {
    cookies().set("Cookies work on QUERY", "yes")
    return [{id:0,
      title: "query test",
      content: "a test for trpc query",
      createdAt: Date.now(),
      updatedAt: Date.now()}]
  }),

  create: publicProcedure
    .input(
      z.object({
        title: z.string().min(1),
        content: z.string().min(1),
      }),
    )
    .mutation(({ ctx, input }) => {
      cookies().set("Cookies work on MUTATION", "No!")
      console.log(cookies().getAll())
      return 200;
    }),
});


After calling both the query and the mutation on frontend you only get the cookie from the Query.
But this gets logged to console.

@acme/nextjs:dev: [
@acme/nextjs:dev:   { name: 'Cookies work on QUERY', value: 'yes', path: '/' },
@acme/nextjs:dev:   { name: 'Cookies work on MUTATION', value: 'No!', path: '/' }
@acme/nextjs:dev: ]
@acme/nextjs:dev: [
@acme/nextjs:dev:   { name: 'Cookies work on QUERY', value: 'yes', path: '/' },
@acme/nextjs:dev:   { name: 'Cookies work on MUTATION', value: 'No!', path: '/' }
@acme/nextjs:dev: ]

(this is after calling the query first then the mutation.)
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

cookies not being set in procedure
propPprop / ❓-help
3y ago
t3-turbo
Surya AshishSSurya Ashish / ❓-help
3y ago
Cookies not being passed on to client
onethreadOonethread / ❓-help
2y ago