sarransh's picture
Fix Cookie SameSite Policy for Iframe Support
eb34199 verified
Raw History Blame Contribute Delete
2.55 kB
import { NextAuthOptions } from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";
import { prisma } from "@/lib/prisma";
import bcrypt from "bcryptjs";
const useSecureCookies = process.env.NEXTAUTH_URL?.startsWith("https://");
const cookiePrefix = useSecureCookies ? "__Secure-" : "";
const hostName = new URL(process.env.NEXTAUTH_URL || "http://localhost:3000").hostname;
export const authOptions: NextAuthOptions = {
providers: [
CredentialsProvider({
name: "Credentials",
credentials: {
email: { label: "Email", type: "email" },
password: { label: "Password", type: "password" }
},
async authorize(credentials) {
if (!credentials?.email || !credentials?.password) return null;
const user = await prisma.user.findUnique({
where: { email: credentials.email }
});
if (!user || !user.passwordHash) return null;
const isValid = await bcrypt.compare(credentials.password, user.passwordHash);
if (!isValid) return null;
return {
id: user.id,
name: user.name,
email: user.email,
image: user.image,
role: user.role
};
}
})
],
cookies: {
sessionToken: {
name: `${cookiePrefix}next-auth.session-token`,
options: {
httpOnly: true,
sameSite: 'none', // Allow cross-site usage (iframe)
path: '/',
secure: true, // Required for SameSite=None
domain: hostName == 'localhost' ? 'localhost' : '.' + hostName // Optional: allows subdomains
}
}
},
callbacks: {
async session({ session, token }) {
if (session.user) {
session.user.id = token.id as string;
session.user.role = token.role as string;
}
return session;
},
async jwt({ token, user }) {
if (user) {
token.id = user.id;
token.role = (user as any).role;
}
return token;
}
},
pages: {
signIn: "/auth/signin",
},
session: {
strategy: "jwt",
},
secret: process.env.NEXTAUTH_SECRET,
};