I am getting this error, running locally a nextjs project, using next-auth v5
Unhandled Runtime Error MissingSecret: Missing secret, please set AUTH_SECRET or config.secret. Read more at https://errors.authjs.dev#missingsecret
But my .env file has (key changed)
AUTH_SECRET="srqoi/XynrMAjcjuMx6T5kGMXRAc+giSoSIxvpESUpA="
also, I can console.log my process.env file and I get, aside others,
this on server terminal/console
{
...
AUTH_SECRET: 'srqoi/XynrMAjcjuMx6T5kGMXRAc+giSoSIxvpESUpA='
}
but it's empty in the browser, when console.log is executed at runtime
what am I doing wrong ?
Context
I am getting the error at this line
export const { auth, signIn, signOut } = NextAuth(authConfig);
this is my authConfig
import { getUser } from "@/services/authService";
import type { NextAuthConfig } from "next-auth";
import Credentials from "next-auth/providers/credentials";
import { z } from "zod";
import dotenv from "dotenv";
dotenv.config();
console.dir(process.env);
export const authConfig = {
pages: {
signIn: "/login",
},
callbacks: {
authorized({ auth, request: { nextUrl } }) {
console.log("running auth/config.js -> callbacks.authorized");
const isLoggedIn = !!auth?.user;
const isOnDashboard = nextUrl.pathname.startsWith("/dashboard");
if (isOnDashboard) {
if (isLoggedIn) return true;
return false; // Redirect unauthenticated users to login page
} else if (isLoggedIn) {
return Response.redirect(new URL("/dashboard", nextUrl));
}
return true;
},
},
providers: [
Credentials({
async authorize(credentials) {
console.log(
"runnning auth/config.ts -> providers.Credentials.authorize - Received credentials:",
credentials
);
const parsedCredentials = z
.object({ email: z.string().email(), password: z.string().min(6) })
.safeParse(credentials);
if (parsedCredentials.success) {
const { email, password } = parsedCredentials.data;
const user = await getUser(email, password);
if (!user) return null;
return user;
}
console.log("Invalid credentials");
return null;
},
}),
],
secret: process.env.AUTH_SECRET,
} satisfies NextAuthConfig;
Resolved adding
to my login form action solved ALL problems.
I suppose this forced my next-auth code to be run also only server side, so it's finding the .env and populating the
process.env