2025.1.7 수요일의 공부기록
Next.js는 파일 기반 라우팅 시스템을 통해 URL 구조를 손쉽게 관리할 수 있다. 이 중 Route Group과 Metadata는 라우팅과 SEO 및 페이지 설정을 더욱 유연하게 관리할 수 있도록 도와주는 기능이다.
Route Group은 Next.js에서 폴더 이름을 괄호로 묶어 사용하여, URL 경로에 표시되지 않도록 만드는 기능이다.
이를 통해 내부적으로는 폴더를 구조화하고, URL에는 영향을 주지 않도록 라우트를 설계할 수 있다.
폴더 이름을 괄호로 묶어서 생성한다:
app/
├── (group)/
│ ├── dashboard/
│ │ └── page.tsx
│ ├── profile/
│ └── page.tsx
├── layout.tsx
(group)
폴더는 URL에 표시되지 않는다./dashboard
경로로 접속하면, 내부적으로는 (group)/dashboard/page.tsx
파일이 렌더링된다./profile
경로로 접속하면 (group)/profile/page.tsx
파일이 렌더링된다.경로 | 실제 파일 경로 |
---|---|
/dashboard | app/(group)/dashboard/page.tsx |
/profile | app/(group)/profile/page.tsx |
Next.js의 메타데이터(metadata)는 각 페이지나 레이아웃에 대한 정보를 설정하는 기능이다.
주로 SEO와 브라우저 동작에 영향을 미치는 설정을 관리하는 데 사용된다.
export const metadata
를 사용하여 메타데이터를 정의한다.
예시: /app/about-us/page.tsx
import Navigation from "../components/navigation";
export const metadata = {
title: "About Us",
};
export default function AboutUs() {
return (
<div>
<h1>About Us</h1>
</div>
);
}
부모와 자식의 메타데이터는 병합된다.
예시: 레이아웃에 메타데이터 추가
// app/layout.tsx
import { Metadata } from "next";
import Navigation from "./components/navigation";
export const metadata: Metadata = {
title: {
template: "%s | Next Movies",
default: "Next Movies",
},
description: "Best movies in the world",
};
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<html lang="en">
<body>
<Navigation />
{children}
</body>
</html>
);
}
결과:
/about-us
경로는 아래와 같이 메타데이터가 병합된다.
About Us
Best movies in the world
메타데이터 템플릿은 반복적으로 사용되는 메타데이터를 효율적으로 관리할 수 있도록 도와준다.
예시: 메타데이터 템플릿
export const metadata: Metadata = {
title: {
template: "%s | Next Movies",
default: "Next Movies",
},
description: "Best movies in the world",
};
동작 결과:
/about-us
페이지의 title: About Us | Next Movies
/not-found
페이지의 title: Not Found | Next Movies
Route Group과 메타데이터는 함께 사용할 때 더욱 유용하다.
Route Group을 통해 URL 구조를 깔끔하게 정리하고, 메타데이터를 중첩 및 병합하여 SEO와 페이지 설정을 최적화할 수 있다.
app/
├── (admin)/
│ ├── dashboard/
│ │ ├── layout.tsx
│ │ └── page.tsx
│ └── profile/
│ └── page.tsx
├── layout.tsx
app/(admin)/dashboard/layout.tsx
:
export const metadata = {
title: 'Admin Dashboard',
description: 'Manage your application settings here.',
};
export default function AdminLayout({ children }: { children: React.ReactNode }) {
return (
<div>
<h1>Admin Area</h1>
{children}
</div>
);
}
결과:
1. /dashboard
경로는 Admin Layout이 적용되며 메타데이터가 병합된다.
2. /profile
경로도 동일한 Admin Layout과 메타데이터가 적용된다.