A demo implementation of SuperTokens with Next.js and tRPC.
๐ See the blog post for a step-by-step walkthrough (Also available in the repo)
This project aims to demonstrate how to integrate SuperTokens into a Nexjs application with tRPC and ensure that Supertoken's session refreshing mechanisms remain intact with the API flow. Its primary purpose is to serve as an educational tool.
This project was bootstrapped with npx create-supertokens-app@latest but amended to use the src directory.
components/trpc/trpcTanstack.provider.tsxcontains the necessary Tanstack Query and tRPC providers for the query client and hooks. Put this up high in your application.- It contains crucial code for optimal functioning with SuperTokens. During unauthenticed requests, a refresh code is sent from the tRPC router and intercepted here, where a session refresh is attempted once followed by a request retry.
components/trpc/trpc.client.tsexposes the tRPC provider and hooks.hooks/useUser.tsexample hook for user queries and mutations.hooks/useSessionCheck.tshelper hook for checking session exists.
server/trpc/trpc.tsMain tRPC configuration.- It contains crucial code for optimal functioning with SuperTokens. During unauthenticed requests, a refresh code (custom status code) is sent from tRPC here and intercepted at the frontend, which triggers a session refresh.
server/trpc/root.tsMain collection point for tRPC routers.server/trpc/index.tsRe-export of tRPC internals and helper types.server/trpc/authErrorCodes.tsCustom auth error states and directives.server/trpc/routerDirectory for tRPC routers.server/trpc/handlersAPI handlers. Split by procedure which contains relevant context.
API handlers are attached to a public or protected procedure, the latter which guarantees the user is logged in at the time of the request (other context dependencies can be added here, such as db adapters). Routers only contain router-logic and wire the relevant procedures to handlers. This allows for easier oversight over API routes and isolating business logic to respective handlers.
Firgrep