NextAuth behind nginx https proxy doesn't get session
I have got my app working in development and now wanted to move everything to production. My Database, Next.js and NGINX all run in docker containers. To create a secure connection I configured nginx to handle SSL and redirect everything to https. Now I'm facing the following problem:
My config:
listen 443 ssl;
server_name localhost;
root /srv/public;
server_tokens off;
ssl_certificate /SSL-Cert/my.crt;
ssl_certificate_key /SSL-Cert/my.key;
location / {
try_files $uri $uri/ @nextjs;
}
location @nextjs {
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto https;
proxy_set_header X-Forwarded-Ssl on;
proxy_set_header Host $http_host;
proxy_redirect off;
proxy_pass http://nextjs;
proxy_cookie_path / "/; HTTPOnly; Secure";
}
}
- When I sign in without the proxy enabled on an http connection everything works fine
- When I turn on the proxy:
- The "Sign in with discord" button redirects me to the same site again but with ?csrf=true at the end
- Clicking it again now redirects to discord correctly
- After logging in a session is created in the database but calling session.user returns null
My config:
- NEXTAUTH_URL='https://production.com'
- discord callback: 'https://production.com/api/auth/callback/discord''
- nginx config:
upstream nextjs {
server 172.17.0.4:3000;
}
server {
# Redirect HTTP requests to HTTPS.
listen 80;
server_name localhost;
root /srv/public;
return 301 https://$host$request_uri;
}
listen 443 ssl;
server_name localhost;
root /srv/public;
server_tokens off;
ssl_certificate /SSL-Cert/my.crt;
ssl_certificate_key /SSL-Cert/my.key;
location / {
try_files $uri $uri/ @nextjs;
}
location @nextjs {
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto https;
proxy_set_header X-Forwarded-Ssl on;
proxy_set_header Host $http_host;
proxy_redirect off;
proxy_pass http://nextjs;
proxy_cookie_path / "/; HTTPOnly; Secure";
}
}