728x90
λ°μν
π‘ Learn Nextμμλ src ν΄λλ₯Ό μ¬μ©νμ§ μλ κ²½μ°, middleware.ts νμΌμ νλ‘μ νΈ λ£¨νΈμ μμΉμν΅λλ€.
κ·Έλ¬λ src ν΄λλ₯Ό μ¬μ©νλ κ²½μ°μλ νμΌμ src ν΄λ λ΄λΆμ μμΉμμΌμΌ ν©λλ€.
λ¬Έμ μ
auth.ts - NextAuth - signIn ν¨μλ μ λλ‘ λμμ νμΌλ middleware.tsμ μ°κ²°λ auth.config.ts νμΌμ΄ λμμμμ΅λλ€.
//auth.ts
async function getUser(email: string): Promise<User | null> {
try {
return await prisma.user.findUnique({where: { uid: 1 }})
} 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 = password === user.password
if (passwordsMatch) return user
}
console.log('Invalid credentials')
return null
},
}),
],
})
//auth.config.ts
export const authConfig = {
pages: {
signIn: '/login',
},
callbacks: {
authorized({ auth, request: { nextUrl } }) {
const isLoggedIn = !!auth?.user
// const isOnDashboard = nextUrl.pathname.startsWith('/product')
const isPublicRoute = publicRoute.includes(nextUrl.pathname)
const isAuthRoute = authRoute.includes(nextUrl.pathname)
if (isPublicRoute && isLoggedIn) {
return Response.redirect(new URL('/', nextUrl))
}
if (isAuthRoute) {
return isLoggedIn
}
// if (isOnDashboard) {
// return isLoggedIn
// // Redirect unauthenticated users to login page
// } else if (isLoggedIn) {
// return Response.redirect(new URL('/product', nextUrl))
// }
return true
},
},
providers: [], // Add providers with an empty array for now
} satisfies NextAuthConfig
// src/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$).*)'],
}
ν΄κ²°
Learn Nextμμλ src ν΄λλ₯Ό μ¬μ©νμ§ μμ middleware.ts νμΌμ μμΉλ₯Ό νλ‘μ νΈ λ£¨νΈμ μμΉνμμ§λ§ src ν΄λλ₯Ό μ¬μ©νλ©΄ src ν΄λ λ΄λΆμ νμΌμ΄ μμΉν΄μΌνλ€.
728x90
λ°μν
'NEXT' μΉ΄ν κ³ λ¦¬μ λ€λ₯Έ κΈ
NEXT JS + Google Analytics Connect Setting (0) | 2024.08.07 |
---|---|
Parallel Routes Modal Difficult Error (0) | 2024.07.25 |
NextJs Next-auth getSession() λ‘κ·ΈμΈ μ 보 νμΈ (0) | 2024.07.23 |
NextJS Prisma PostgreSQL μ°κ²° λ° Migrate (0) | 2024.07.09 |
next-themes Hydration failed Error (0) | 2024.05.31 |