Thimo_oT
tRPC3y ago
6 replies
Thimo_o

How do I setup App router + TRPC + Lucia Auth? (protected routes)

I'm trying to setup tRPC with Lucia in app router but I struggle to make protected routes work.

I made a trpc context where I put lucia session and a getDefaultSession function to get the session

export const getDefaultSession = cache((req: NextRequest) => {
  const authRequest = auth.handleRequest({
    request: req,
    cookies,
  })
  return authRequest.validate()
})

const createInnerTRPCContext = (opts: CreateContextOptions) => {
  return {
    session: opts.session,
  }
}

export const createTRPCContext = async (req: NextRequest) => {
  const session = await getDefaultSession(req)

  return createInnerTRPCContext({
    session,
  })
}


I wrote a isAuth function to make the protected procedure

const enforceUserIsAuthed = t.middleware(({ ctx, next }) => {
  if (!ctx.session || !ctx.session?.user) {
    throw new TRPCError({ code: "UNAUTHORIZED" })
  }
  return next({
    ctx: {
      // infers the `session` as non-nullable
      session: { ...ctx.session, user: ctx.session.user },
    },
  })
})

export const protectedProcedure = t.procedure.use(enforceUserIsAuthed)


and added it in my route.ts handler

const handler = (req: NextRequest) =>
  fetchRequestHandler({
    endpoint: "/api/trpc",
    req,
    router: appRouter,
    createContext: () => createTRPCContext(req),
  })

export { handler as GET, handler as POST }


But the session is not passed into ctx resulting in always getting the unauthorized error. Does someone know what I did wrong to make this work?
Was this page helpful?