Back

Next.js 14 + tRPC + Appwrite: Session cookie not being set or persisted

  • 0
  • Self Hosted
  • Auth
Dan
17 Oct, 2024, 08:10

I'm building a Next.js 14 application with tRPC and Appwrite for authentication as a way to further my learning, so I may have aspects of this wrong. This is a self-hosted 1.6 version of Appwrite. The T3 Stack was used as a starting point for this app.

I'm encountering an issue where the session cookie is not being set or persisted after a successful login.

Environment:

  • Next.js 14 (App Router)
  • tRPC
  • Appwrite for authentication
  • Running on localhost with custom subdomain (my.example.localhost:3000)

Steps to reproduce:

  1. User navigates to the sign-in page
  2. User enters credentials and submits the form
  3. The server successfully authenticates with Appwrite and receives a session token
  4. The server attempts to set a cookie with the session token
  5. The user is redirected to the account page
  6. The middleware checks for the presence of the session cookie
  7. The cookie is not found, and the user is redirected back to the sign-in page

Expected behaviour: After successful authentication, the session cookie should be set and persisted, allowing the user to access protected routes.

Actual behavior: The session cookie is not being set or persisted, resulting in the user being unable to access protected routes and getting stuck in a redirect loop.

Relevant code (see attached files):

  1. Auth Router (src/server/api/routers/auth.ts):
  2. Middleware (src/middleware.ts):
  3. Sign-in Page (src/app/(auth)/signin/page.tsx):

Server logs (see attached files):

Browser console logs (see attached files):

I've tried setting the cookie using both the cookies() API from Next.js and manually setting the Set-Cookie header. Neither approach seems to result in the cookie being set or persisted in the browser.

Any help or insights would be greatly appreciated. Thank you!

TL;DR
Developers building a Next.js 14 app with tRPC and Appwrite are facing an issue where the session cookie is not being set or persisted after a successful login. Despite trying different methods to set the cookie, including the `cookies()` API and manual `Set-Cookie` header, the problem persists. This prevents users from accessing protected routes. If you have insights or solutions, your assistance would be greatly appreciated.
Dan
17 Oct, 2024, 08:12

I appreciate a markdown file isn't the easiest way to access the code, so I have a gist with the same code here: https://gist.github.com/danmaby/f34c175459164941f7cbd3a43808b3ed.

Reply

Reply to this thread by joining our Discord

Reply on Discord

Need support?

Join our Discord

Get community support by joining our Discord server.

Join Discord

Get premium support

Join Appwrite Pro and get email support from our team.

Learn more