I have done the tutorial of creating a dashboard with NextJS
- https://nextjs.org/learn/dashboard-app/adding-authentication
At the end, I have added a auth system.
Creating the file auth.config.ts
import type { NextAuthConfig } from 'next-auth';
export const authConfig = {
pages: {
signIn: '/login',
},
callbacks: {
authorized({ auth, request: { nextUrl } }) {
const isLoggedIn = !!auth?.user;
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;
},
},
providers: [],
} satisfies NextAuthConfig;
then a auth.ts
import NextAuth from 'next-auth';
import Credentials from 'next-auth/providers/credentials';
import { authConfig } from './auth.config';
import { z } from 'zod';
import { sql } from '@vercel/postgres';
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;
},
}),
],
});
ended with a middleware.ts
import NextAuth from 'next-auth';
import { authConfig } from './auth.config';
export default NextAuth(authConfig).auth;
export const config = {
// https://nextjs.org/docs/app/building-your-application/routing/middleware#matcher
matcher: ['/((?!api|_next/static|_next/image|.*\.png$).*)'],
};
on my page dashboard/page.tsx
I get the auth user
const user = await auth();
console.log(user);
I have this result
{
user: { name: 'User toto', email: '[email protected]' },
expires: '2025-01-12T13:47:17.724Z'
}
During the login, I return a User
type from @/app/lib/definitions
but in my page I got a User
type from auth-core
and my id
is empty
Name and email are filled correctly but not the identifier, how can I get the id of the logged user ?
I have created a session(session_id, user_id)
table in my database, I save the session_id inside a cookie client side and I know which user is logged, but it should be easier to directly get the id as name and email.
Thanks
1