I'm experiencing an issue with NextAuth.js (v4) in a Next.js 13 app when the site is embedded in an iframe.
✅ Expected Behavior: Login should work the same inside and outside an iframe.
❌ Actual Behavior: When embedded in an iframe, users get redirected back to the login page after attempting to sign in. Outside the iframe, login works fine.
Referrer-Policy
headerReferrer-Policy: strict-origin-when-cross-origin
causes a 400 Bad Request
from nginx when calling /api/auth/providers
.headers()
API:async headers() {
return [
{
source: '/:path*',
headers: [
{ key: 'Access-Control-Allow-Origin', value: '*' },
{ key: 'Access-Control-Allow-Methods', value: 'GET, POST, PUT, DELETE, OPTIONS' },
{ key: 'Access-Control-Allow-Headers', value: 'Content-Type, Authorization' },
{ key: 'Cross-Origin-Resource-Policy', value: 'cross-origin' },
{ key: 'Cross-Origin-Embedder-Policy', value: 'unsafe-none' },
],
},
];
},
<iframe content-security-policy="default-src * 'unsafe-inline' 'unsafe-eval';" referrerpolicy="unsafe-url" src="..."></iframe>
Initially, I tried modifying [...nextauth].ts
to remove Referrer-Policy
, but I wasn't sure if the function was executing.
However, after testing further, the function does apply, but now I get a new error even when not using an iframe:
[next-auth][error][CLIENT_FETCH_ERROR]
JSON.parse: unexpected character at line 1 column 1 of the JSON data
Object { error: {…}, url: "/api/auth/session", message: "JSON.parse: unexpected character at line 1 column 1 of the JSON data", client: true }
Here’s the updated [...nextauth].ts
function:
import type { NextApiRequest, NextApiResponse } from 'next';
import NextAuth from 'next-auth';
import { authOptions } from '../../../../utils/authOptions';
export default async function auth(req: NextApiRequest, res: NextApiResponse) {
console.log('Auth API route hit');
res.removeHeader('Referrer-Policy');
delete req.headers['Referrer-Policy'];
return await NextAuth(req, res, authOptions);
}
CLIENT_FETCH_ERROR
when NextAuth tries to fetch /api/auth/session
.Referrer-Policy
header?[...nextauth].ts
result in a CLIENT_FETCH_ERROR
for /api/auth/session
?Any help or suggestions would be greatly appreciated!