PromleeBlog
sitemap
aboutMe

posting thumbnail
Next js 앱 라우팅 알아보기
Learn about routing Nextjs apps

📅

🚀

들어가기 전에 🔗

Next.js 13 버전부터 지원하는 App 라우팅을 사용해 보자.
Next.js는 파일 시스템 라우팅을 사용하므로 애플리케이션의 라우팅은 파일 구조에 따라 결정된다.
앱 라우팅 방식 서버 컴포넌트, 서버 액션, Suspense 등의 기술을 지원한다.
이 포스팅에서는 기본적인 사용법을 작성하였다.

🚀

루트 페이지 설정 🔗

기본적으로 생성된 app/디렉토리 내부의 page.tsx파일과 layout.tsx 파일을 사용하여 루트 디렉토리(/)를 설정할 수 있다.
app/layout.tsx
export default function RootLayout({children,}: {children: React.ReactNode}) {
  return (
    <html lang="en">
      <body>{children}</body> 
	{/* html, body 태그를 사용하여 레이아웃을 구성*/}
	{/* children은 page.tsx 내부의 컴포넌트를 받아서 레이아웃을 구성한다. */}
    </html>
  )
}
app/page.tsx
export default function Page() {
	return <p>Root Page</p>
}
👨‍💻
layout.tsx
파일이 없어도, Next.js는 실행 시 자동으로 레이아웃을 생성해준다.
npm run dev로 실행 후 http://localhost:3000/ 에 접속하면 Root Page가 출력된다.

🚀

라우팅 정의하기 🔗

위에서 언급했다시피 Next.js는 파일 시스템 라우팅을 사용하므로 라우팅은 파일(폴더) 구조에 따라 결정된다.
app/의 하위 폴더를 생성하여 라우팅을 생성 할 수 있다.
app/example/page.tsx
export default function ExamplePage() {
	return <p>Example Page</p>
}
npm run dev로 실행 후 http://localhost:3000/example 에 접속하면 Example Page가 출력된다.

동적 라우팅 🔗

동적 라우팅은 폴더 이름에 대괄호를 사용하여 정의할 수 있다.
app/example/[slug]/page.tsx
export default function SlugPage({ params }: { params: { slug: string } }) {
	return <p>{params.slug} Page</p>
}
npm run dev로 실행 후 http://localhost:3000/example/hello 에 접속하면 hello Page가 출력된다.

🚀

라우팅 핸들러 사용 API 라우팅 🔗

API 라우팅은 app/api/ 디렉토리를 생성하여 사용할 수 있다.
app/api/hello.ts
import { NextResponse } from "next/server";
 
export async function GET() {
  return NextResponse.json({ message: "Hello World" });
}
npm run dev로 실행 후 http://localhost:3000/api/hello 에 접속하면 {"message":"Hello World"}가 출력된다.
🖐️
route.ts 파일은 page.tsx 파일과 같은 경로에 존재할 수 없다.

🚀

참고 🔗