본문 바로가기

nextjs

[Next.js 14 App] API 함수 이름

nextjs 14 app router 는 폴더가 src/pages가 아닌 src/app 인 경우에 해당한다.

이때 api 라우팅은 폴더 아래에 route.js 타입스크립트를 사용한 경우 route.ts 이란 파일을 만든후

파일에 GET, POST, DELETE, PATCH 등 대문자로 작성된 페치 타입을 비동기/동기 함수로 내보낸다

예시:

 

export async function GET(req: Request) {
	return NextResponse.json({
    	message: "hello!"	
    })
}

 

한 파일에선 중복된 함수는 안되지만

여러 함수는 동시에 존재할수있다

 

api 에서 새션 가져오기:

 

 

next auth 를 사용했을떄 NextAuth(여기 안쪽에 있는 코드를)

src/lib/authOptions.ts or *.js 를 만들어서

export const authOptions : NextAuthOptions = {
	providers: [
    	GithubProvider({
    	  clientId: process.env.GITHUB_ID!,
    	  clientSecret: process.env.GITHUB_SECRET!
    	}),
    	GoogleProvider({
    	  clientId: process.env.GOOGLE_CLIENT_ID!,
    	  clientSecret: process.env.GOOGLE_CLIENT_SECRET!
    	}),
    ]
}

이런느낌으로 구성한뒤

본래 auth/[...nextauth] 에서

import NextAuth from "next-auth";
import { authOptions } from "@/lib/authOptions";

const handler = NextAuth(authOptions);

export { handler as GET, handler as POST };

 

그러면 api 에서

const session = await getServerSession(authOptions) // import { getServerSession } from "next-auth"

 

를 이용해서 세션을 가져올수 있다

 

[/post/어떤-포스트] 경로로 포스트 정보를 가져오고싶을떈 

 

폴더 구성을

post

  ㄴ[id]     

         ㄴ route.ts   or *.js

로 구성한뒤

 

export async function 함수이름(req: Request, { id } :  { id: string })

폴더 대괄호 사이에 있는 글자로 주어지는것이여서 

폴더를 [file] 로 작성할시 

export async function 함수이름(req: Request, { file } :  { file: string })

로 작성해야한다