alexjkni.dev
alexjkni.dev

Reputation: 35

response cookie not persisting with Elysia & TRPC

So picked up Bun recently, have setup Remix + Elysia wrapped TRPC + Prisma to build out a project.

I've created a pretty simple login system with the intention to implement the JWT cookie flow. However I'm running into a problem where the cookie won't persist even though it's present in the response & acknowledged by network tools as a cookie. It just refuses to appear in storage & isn't sent with the next request.

For context, here's the network info

Headers network headers

Cookies network cookies

Stored cookies stored cookies

I've got the below as my Elysia setup

const CONFIG = {
  host: '127.0.0.1',
  port: 3000,
  protocol: 'http'
}

new Elysia()
  .use(
    cors({
      credentials: true,
      origin: true,
    }
  ))
  .use(
    trpc(
      router,
      {
        createContext,
      }
    )
  )
  .listen({
    hostname: CONFIG.host,
    port: CONFIG.port,
  })

console.log(`listening on http://${CONFIG.host}:${CONFIG.port}`)

with the createContext simply being to pass context through

export async function createContext(opts: FetchCreateContextFnOptions) {

  return opts
}

then in my trpc login query I've got

ctx.resHeaders.set(
  'Set-Cookie', 
  'hello=world; SameSite=Lax; Path=/; Max-Age=3600; HttpOnly'
)

Upvotes: 0

Views: 392

Answers (1)

alexjkni.dev
alexjkni.dev

Reputation: 35

Managed to get it working after test hitting the actual trpc endpoint and seeing the cookie get set as it should which led me down the thought process that it's a problem with the trpcClient setup.

Included the credentials with the fetch associated with the trpcClient

export const client = createTRPCClient<Router>({
  links: [
    httpBatchLink({
      fetch: (url, init) => fetch(url, {
        ...init,
        credentials: 'include'
      }),
      url: 'http://127.0.0.1:3000/trpc'
    }),
  ]
})

and tweaked the cors plugin config for the server

new Elysia()
  .use(
    cors({
      allowedHeaders: ['Content-Type'],
      credentials: true,
      origin: /^http:\/\/127\.0\.0\.1:8080$/,
    }
  ))
  .use(
    trpc(
      router,
      {
        createContext,
      }
    )
  )
  .listen({
    hostname: CONFIG.host,
    port: CONFIG.port,
  })

Upvotes: 0

Related Questions