I’m running a Next.js v14+ with Typescript application and I’m using NextAuth.js to handle users sessions.
At the very start I wasn’t handling https and cors in any way, then I noticed that even if my application worked perfectly, if you opened it trough a link from any mobile app, visiting the website through its webview, the login just stopped to work, returning 200 (no matter which credentials were used) and an empty session object.
I tried to handle CORS related issues thinking it could solve the problem but now that the login correctly works even with the new implementations, the webviews’ issue still persists.
- next.config.mjs
/** @type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: false,
async headers() {
return [
{
// matching all API routes
source: "/api/auth/:path*",
headers: [
{ key: "Access-Control-Allow-Credentials", value: "true" },
{ key: "Access-Control-Allow-Origin", value: "*" },
{ key: "Access-Control-Allow-Methods", value: "GET, POST, OPTIONS" },
{ key: "Access-Control-Allow-Headers", value: "Authorization, Content-Type" },
],
},
];
},
};
export default nextConfig;
- libauth.ts
import { AuthOptions } from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";
export const authOptions: AuthOptions = {
providers: [
CredentialsProvider({
name: 'Credentials',
credentials: {
username: { label: "Username", type: "text", placeholder: "Username" },
password: { label: "Password", type: "password", placeholder: "Password" }
},
async authorize(credentials, req) {
//Authorize Code Which Works
}
})
],
session: {
strategy: 'jwt',
maxAge: 30 * 24 * 60 * 60, // Scadenza del cookie (30 giorni)
},
secret: process.env.JWT_SECRET,
pages: {
signIn: '/accedi'
},
cookies: process.env.NODE_ENV === "production" ? {
sessionToken: {
name: "__Secure-next-auth.session-token",
options: {
httpOnly: true,
sameSite: 'None',
secure: true,
path: '/',
},
},
csrfToken: {
name: "__Host-next-auth.csrf-token",
options: {
httpOnly: true,
sameSite: 'None',
secure: true,
path: '/',
},
},
} : {},
callbacks: {
async jwt({ token, trigger, user }) {
if (!token.user && user) {
token.user = user;
}
if (trigger === "update" || (((Date.now() - (token.iat as number * 1000)) / (1000 * 60) >= 15))) {
//Update handling
}
return token;
},
async session({ session, token }) {
if (token?.user) {
session.user = token.user;
}
return session;
},
}
};
- appapiauth[…nextauth]route.ts
import NextAuth from "next-auth";
import { authOptions } from "@/lib/auth";
const handler = NextAuth(authOptions) as never;
export { handler as GET, handler as POST };
The answer makes me feel so stupid… the website url was getting opened under the http protocol instead of the https, opening it in the right protocol solves the problem immediately.
A good thing to do could be to implement an automated redirect to the https version of the website.