[Next.js] Next Auth와 Middleware

insung·2024년 6월 17일

Nextjs

목록 보기
14/21

NextAuth와 middleware (페이지 접근 권한 제어)

auth.ts
import NextAuth from "next-auth" // npm i next-auth@5 @auth/core
import CredentialsProvider from "next-auth/providers/credentials";

export const {
	handlers: {GET, POST}, // api 라우트
	auth : ..., // 로그인 했는지 안했는지 알아내는 용 
	signIn, // 로그인 하는 용
	

} = NextAuth({
	pages: {
	signIn : '/i/flow/login',
	newUser: '/i/flow/singup',
	},
	providers: [
	CredentialsProvider({
		async authroize(credentails)
		const authResponse= await fetch("${process.env.NEXT_PUIBLIC_BASE_URL}/users/login",{
		
			method: "POST",
			headers: {
				"Content-Type" : "application/json",
			},
			body : JSON.stringify({
				id: credentials.username,
				password: credentails.password
			});
		}
		
		if(!authResponse.ok) {
			return null
		}
		
		
		
		const user = await authResponse.json()
		// 로그인 한 사용자 정보 저장
		return user
	})
	
	
	
	
	]
})

middleware.ts

export {auth as middleware} from "./auth"
// auth => 로그인을 했는지 안했는지 알아내는 용

export const config = {
	// middleware를 적용할 라우트 (로그인을 해야만 접근가능한 페이지 등)
	matcher: ['/compose/tweet', '/home', '/explore', '/messages', '/search'],
	
}
src/app/api/auth/[...nextauth]/route.ts

import {GET, POST} from @/auth
// api/auth/어떤경로든 호출 
profile
안녕하세요 프론트엔드 관련 포스팅을 주로 하고 있습니다

0개의 댓글