laptop with plant
Shares

Fix for Next-Auth Error Behind Nginx Proxy

Last updated: Jul 6, 2024

Next-Auth can be problematic when run behind a proxy such as Nginx. In this article, we go over the issue and how I, finally, solved it.

The Setup

I run this website, gause.dev, on a server using Nginx as a proxy to a pm2 process that runs my Next.js application. Because it is behind a proxy, I ran into a problem where any attempts at accessing the auth endpoint ended in a 500 error. And we all know that is bad

Stack: Node v18.17.0 (also tried v21.6.1), Next.js 14.1.0, Next-Auth 5.0.0-beta.8

The Error

Checking the pm2 logs, pm2 logs gause.dev, showed two different errors.

[auth][error] UntrustedHost: Host must be trusted.

and

TypeError: i0 is not a constructor

The Solution

I struggled with these errors for many days. Only after walking away from the problem and coming back to it with a clear mind, did I finally find the solution. That and a bit of luck. Google searching had done me no good.

The "UntrustedHost" error was simple enough, albeit it took me quite a while to realize it was because the site is being run being a proxy at localhost. Editing the auth config to include the normally dangerous "trustHost" option was the key.

  debug: false,
  trustHost: true,
  providers: [ ... ]

That solved one issue but led to the "is not a constructor error". This one was very hard to solve. I spent hours trying various things. The solution ended up being to remove the NEXTAUTH_URL, and NEXTAUTH_URL_INTERNAL environment variables. Apparently they aren't required anymore.

My .env file before the change:

NEXTAUTH_SECRET=....
NEXTAUTH_URL=http://localhost:3000
NEXTAUTH_URL_INTERNAL=http://localhost:3000
NODE_ENV=production

And after:

NEXTAUTH_SECRET=....
# DO NOT SET THESE URLS!!!!
#NEXTAUTH_URL=http://localhost:3000
#NEXTAUTH_URL_INTERNAL=http://localhost:3000
NODE_ENV=production

And problem solved. Seems easy in retrospect, but that is usually the case. Now if only I paid myself by the hour....