Auth in nextjs/learn not working?
Answered
Alligator mississippiensis posted this in #help-forum
Alligator mississippiensisOP
import type { NextAuthConfig } from 'next-auth';
export const authConfig = {
providers: [],
pages: {
signIn: '/login',
},
callbacks: {
authorized({ auth, request: { nextUrl } }) {
console.log(auth, 'auth');
const isLoggedIn = !!auth?.user;
console.log(isLoggedIn);
const isOnDashboard = nextUrl.pathname.startsWith('/dashboard');
if (isOnDashboard) {
if (isLoggedIn) return true;
return false;
} else if (isLoggedIn) {
return Response.redirect(new URL('/dashboard', nextUrl));
}
return true;
},
},
} satisfies NextAuthConfig;And this is my auth.ts
import NextAuth from 'next-auth';
import Credentials from 'next-auth/providers/credentials';
import { authConfig } from './auth.config';
import { sql } from '@vercel/postgres';
import { z } from 'zod';
import type { User } from '@/app/lib/definitions';
import bcrypt from 'bcrypt';
async function getUser(email: string): Promise<User | undefined> {
try {
const user = await sql<User>SELECT * from USERS where email=${email};
return user.rows[0];
} catch (error) {
console.error('Failed to fetch user:', error);
throw new Error('Failed to fetch user.');
}
}
export const { auth, signIn, signOut } = NextAuth({
...authConfig,
providers: [
Credentials({
async authorize(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);
if (!user) return null;
const passwordsMatch = await bcrypt.compare(password, user.password);
if (passwordsMatch) return user;
}
console.log('Invalid credentials');
return null;
},
}),
],
});Everything was copy pasted from nextjs/learn
Answered by Chausie
this worked for me https://github.com/vercel/next-learn/issues/252#issuecomment-1783617501
6 Replies
Alligator mississippiensisOP
console.log(auth, 'auth'); this console.log is returning null
Chausie
having the exact same issue here
Chausie
did you get it working ?
Alligator mississippiensisOP
No :/
Chausie
this worked for me https://github.com/vercel/next-learn/issues/252#issuecomment-1783617501
Answer
Yep, adding NEXTAUTH_URL, somehow, fixed this issue for me as well...