환경 변수는 코드 밖 파일에 적어 두고 process.env.이름으로 읽는 값입니다. 이 레슨은 프로젝트 뿌리의 .env.local에 값 둘을 두고, 그 값이 받은 HTML과 브라우저 화면 가운데 어디까지 가는지 봅니다.
바깥 서비스에 들어가는 비밀 키처럼 코드에 그대로 적으면 안 되는 값이 있습니다. 코드에 적으면 코드를 git에 올릴 때 키도 같이 올라갑니다. 앱 이름처럼 코드를 고치지 않고 바꾸고 싶은 값도 있습니다. 이런 값은 코드 밖 파일에 두고 읽습니다. 그런데 서버와 브라우저에서 두 번 그리는 클라이언트 컴포넌트가 그 값을 읽으면 어떻게 될까요?
1.env.local과 process.env
프로젝트 뿌리, 곧 package.json과 같은 자리에 VS Code 탐색기의 새 파일로 .env.local을 만듭니다. 맥 Finder는 점으로 시작하는 파일을 숨기고, 윈도 파일 탐색기로 만들면 이름 끝에 .txt가 숨어 붙기 쉽습니다. 한 줄에 이름=값 하나씩 적습니다. 아래 abc123은 지어낸 값입니다.
SECRET_KEY=abc123
NEXT_PUBLIC_APP_NAME=보관함
SECRET_KEY는 남에게 보이면 안 되는 비밀 키라고 칩니다.NEXT_PUBLIC_APP_NAME은 앱 이름입니다.- Next.js가 이 파일을 읽어
process.env에 넣습니다(Next.js 문서 Environment Variables — 'loading environment variables from.env*files intoprocess.env'). 코드에서는process.env.SECRET_KEY처럼 읽습니다. - 이름이
NEXT_PUBLIC_으로 시작하지 않는 값은 서버(Node.js)에서만 읽힙니다(같은 문서 — 'only available in the Node.js environment'). - 템플릿의
.gitignore에는.env*줄이 있습니다. 그래서 이 파일은 git에 올라가지 않습니다.
앱 이름을 찍는 클라이언트 컴포넌트 components/Show.tsx를 만들어 루트 레이아웃의 바닥글에 둡니다. 이 컴포넌트는 단원 9에서 지웁니다.
'use client';
function Show() {
const name =
process.env
.NEXT_PUBLIC_APP_NAME;
return <p>{`앱: ${name}`}</p>;
}
export default Show;…
import Show from
'@/components/Show';
…
바닥글
<Show />
…켜 둔 개발 서버도 저장한 뒤 터미널에 Reload env: .env.local을 찍고 새 값을 읽습니다. 그 줄이 서기 전에 연 쪽은 옛 값을 씁니다. 서버가 읽은 파일을 배너에서도 보려고, 개발 서버를 Ctrl+C로 끄고 npm run dev로 다시 띄운 뒤 /stats를 엽니다.
app/layout.tsx 전체 · 화면 · 서버 터미널
아래는 <Show />를 둔 루트 레이아웃, /stats를 연 뒤 화면에 보이는 <body> 안 HTML, 서버 터미널입니다. 시간은 다를 수 있습니다.
import type {
Metadata,
} from 'next';
import Image from 'next/image';
import {
Noto_Sans_KR,
} from 'next/font/google';
import './globals.css';
import TabBar from
'@/components/TabBar';
import Show from
'@/components/Show';
const noto = Noto_Sans_KR({
subsets: ['latin'],
});
export const
metadata: Metadata = {
title: {
template:
'%s · 레시피 보관함',
default: '레시피 보관함',
},
description:
'내 레시피를 모아 두는 곳',
};
function RootLayout({
children,
}: LayoutProps<'/'>) {
return (
<html lang="ko">
<body
className={
noto.className
}
>
<TabBar />
{children}
<footer>
바닥글
<Show />
<Image
src="/next.svg"
alt="Next.js"
width={100}
height={20}
/>
</footer>
</body>
</html>
);
}
export default RootLayout;<nav><a href="/recipes">목록</a>·<a href="/stats">▸ 통계</a></nav><h1>통계</h1><p>모두 4개</p><footer>바닥글<p>앱: 보관함</p><img alt="Next.js" loading="lazy" width="100" height="20" decoding="async" data-nimg="1" src="/next.svg"></footer>> recipe-box-next@0.1.0 dev
> next dev
▲ Next.js 16.4.6 (Turbopack)
- Local: http://localhost:3000
- Network: http://127.131.113.34:3000
- Environments: .env.local
✓ Ready in 209ms
✓ Running next.config.ts took 1027ms
- Cache Components enabled
- Partial Prefetching enabled
레시피 파일 읽음
Cache 레시피 파일 읽음
GET /stats 200 in 163ms (next.js: 60ms, application-code: 103ms)
Cache 레시피 파일 읽음
Cache 레시피 파일 읽음
배너에 - Environments: .env.local 줄이 더 붙었습니다. 이 서버가 읽은 환경 변수 파일입니다. 바닥글에는 앱: 보관함이 섰습니다. 이름이 NEXT_PUBLIC_으로 시작하니, 브라우저에서 다시 그린 Show도 같은 값을 읽었습니다.
2클라이언트 컴포넌트가 비밀 값을 읽으면
Show가 앱 이름 대신 비밀 키를 찍게 바꿉니다.
…
function Show() {
const key =
process.env.SECRET_KEY;
return <p>{`키: ${key}`}</p>;
}
…개발 서버를 켜 둔 채 저장하고 /stats를 새로 고칩니다.
.env.local · Show.tsx · 루트 레이아웃 · 받은 HTML · 콘솔 · 화면
아래는 1절의 .env.local과 루트 레이아웃, 바꾼 Show, 받은 HTML(다듬음), 브라우저 콘솔, 화면에 보이는 <body> 안 HTML입니다.
SECRET_KEY=abc123
NEXT_PUBLIC_APP_NAME=보관함
import type {
Metadata,
} from 'next';
import Image from 'next/image';
import {
Noto_Sans_KR,
} from 'next/font/google';
import './globals.css';
import TabBar from
'@/components/TabBar';
import Show from
'@/components/Show';
const noto = Noto_Sans_KR({
subsets: ['latin'],
});
export const
metadata: Metadata = {
title: {
template:
'%s · 레시피 보관함',
default: '레시피 보관함',
},
description:
'내 레시피를 모아 두는 곳',
};
function RootLayout({
children,
}: LayoutProps<'/'>) {
return (
<html lang="ko">
<body
className={
noto.className
}
>
<TabBar />
{children}
<footer>
바닥글
<Show />
<Image
src="/next.svg"
alt="Next.js"
width={100}
height={20}
/>
</footer>
</body>
</html>
);
}
export default RootLayout;'use client';
function Show() {
const key =
process.env.SECRET_KEY;
return <p>{`키: ${key}`}</p>;
}
export default Show;<nav><a href="/recipes">목록</a>·<a href="/stats">▸ 통계</a></nav><h1>통계</h1><template id="B:0"></template><p>세는 중</p><footer>바닥글<p>키: abc123</p><img alt="Next.js" loading="lazy" width="100" height="20" decoding="async" data-nimg="1" src="/next.svg"/></footer><div hidden id="S:0"><p>모두 4개</p></div>[Cache] 레시피 파일 읽음
[잡히지 않은 오류] Error: Hydration failed because the server rendered text didn't match the client. As a result this tree will be regenerated on the client. This can happen if a SSR-ed Client Component used:
- A server/client branch `if (typeof window !== 'undefined')`.
- Variable input such as `Date.now()` or `Math.random()` which changes each time it's called.
- Date formatting in a user's locale which doesn't match the server.
- External changing data without sending a snapshot of it along with the HTML.
- Invalid HTML tag nesting.
It can also happen if the client has a browser extension installed which messes with the HTML before React loaded.
https://react.dev/link/hydration-mismatch
...
<HotReload globalError={[...]} webSocket={WebSocket} staticIndicatorState={{pathname:null, ...}}>
<AppDevOverlayErrorBoundary globalError={[...]}>
<ReplaySsrOnlyErrors>
<DevRootHTTPAccessFallbackBoundary>
<HTTPAccessFallbackBoundary notFound={<NotAllowedRootHTTPFallbackError>}>
<HTTPAccessFallbackErrorBoundary pathname="/stats" notFound={<NotAllowedRootHTTPFallbackError>} ...>
<RedirectBoundary>
<RedirectErrorBoundary router={{...}}>
<Head>
<__next_root_layout_boundary__>
<SegmentViewNode type="layout" pagePath="layout.tsx">
<SegmentTrieNode>
<link>
<script>
<script>
<RootLayout>
<html lang="ko">
<body className="noto_sans_...">
<TabBar>
<OuterLayoutRouter>
<footer>
<Show>
<p>
+ 키: undefined
- 키: abc123
...
...
<nav><a href="/recipes">목록</a>·<a href="/stats">▸ 통계</a></nav><h1>통계</h1><p>모두 4개</p><footer>바닥글<p>키: undefined</p><img alt="Next.js" loading="lazy" width="100" height="20" decoding="async" data-nimg="1" src="/next.svg"></footer>받은 HTML의 바닥글에 키: abc123이 그대로 실렸습니다. 클라이언트 컴포넌트도 첫 방문에는 서버가 먼저 그려 HTML로 보냅니다(Next.js 규칙 5 — 하이드레이션). 서버에는 SECRET_KEY가 있어 그때 값이 읽혔습니다. 받은 HTML은 누구나 페이지 소스 보기로 봅니다.
브라우저에서 다시 그린 Show는 키: undefined를 그렸습니다. 브라우저로 가는 JS에는 NEXT_PUBLIC_이 아닌 값이 없습니다. 두 번 그린 글이 달라 콘솔에 하이드레이션 오류가 찍혔습니다(+가 브라우저, -가 서버 — 하이드레이션 오류). 화면은 브라우저 판으로 바뀌었지만, 비밀 키는 이미 받은 HTML에 실려 나갔습니다. 비밀 값은 서버에서만 도는 코드에서 읽고, 클라이언트 컴포넌트에서는 읽지 않습니다.
다 봤으면 components/Show.tsx를 1절 판(앱 이름)으로 되돌립니다.
해 보기 — server-only로 막기
비밀 값을 읽는 코드를 한 파일에 모으고, 그 파일 맨 위에 import 'server-only';를 둡니다. 클라이언트 컴포넌트가 이 파일을 끌어오면 빌드가 멈춥니다(Next.js 문서 Server and Client Components — 'there will be a build-time error'). 이 판의 Next.js는 server-only를 따로 설치하지 않아도 알아봅니다(같은 문서 — 'installing server-only or client-only is optional').
새 파일 lib/secret.ts를 만들고, Show가 그 함수를 부르게 바꿉니다.
import 'server-only';
export const secretKey = () =>
process.env.SECRET_KEY;'use client';
import {
secretKey,
} from '@/lib/secret';
function Show() {
const key = secretKey();
return <p>{`키: ${key}`}</p>;
}
export default Show;개발 서버를 Ctrl+C로 끄고 npm run build를 돌립니다.
.env.local · 루트 레이아웃 · 빌드 출력
아래는 1절의 .env.local과 루트 레이아웃, 빌드 출력입니다. 시간은 다를 수 있습니다.
SECRET_KEY=abc123
NEXT_PUBLIC_APP_NAME=보관함
import type {
Metadata,
} from 'next';
import Image from 'next/image';
import {
Noto_Sans_KR,
} from 'next/font/google';
import './globals.css';
import TabBar from
'@/components/TabBar';
import Show from
'@/components/Show';
const noto = Noto_Sans_KR({
subsets: ['latin'],
});
export const
metadata: Metadata = {
title: {
template:
'%s · 레시피 보관함',
default: '레시피 보관함',
},
description:
'내 레시피를 모아 두는 곳',
};
function RootLayout({
children,
}: LayoutProps<'/'>) {
return (
<html lang="ko">
<body
className={
noto.className
}
>
<TabBar />
{children}
<footer>
바닥글
<Show />
<Image
src="/next.svg"
alt="Next.js"
width={100}
height={20}
/>
</footer>
</body>
</html>
);
}
export default RootLayout; Creating an optimized production build ...
> Build error occurred
Error: Turbopack build failed with 2 errors:
./lib/secret.ts:1:1
Error: You're importing a module that depends on "server-only". This API is only available in Server Components in the App Router, but you are using it in the Pages Router.
Learn more: https://nextjs.org/docs/app/building-your-application/rendering/server-components
> 1 | import 'server-only';
| ^^^^^^^^^^^^^^^^^^^^^
2 |
3 | export const secretKey = () =>
4 | process.env.SECRET_KEY;
Ecmascript file had an error
Import traces:
Client Component Browser:
./lib/secret.ts [Client Component Browser]
./components/Show.tsx [Client Component Browser]
./components/Show.tsx [Server Component]
./app/layout.tsx [Server Component]
Client Component SSR:
./lib/secret.ts [Client Component SSR]
./components/Show.tsx [Client Component SSR]
./components/Show.tsx [Server Component]
./app/layout.tsx [Server Component]
./lib/secret.ts:1:1
Error: 'server-only' cannot be imported from a Client Component module
> 1 | import 'server-only';
| ^^^^^^^^^^^^^^^^^^^^^
2 |
3 | export const secretKey = () =>
4 | process.env.SECRET_KEY;
It should only be used from a Server Component.
Import traces:
Client Component Browser:
./lib/secret.ts [Client Component Browser]
./components/Show.tsx [Client Component Browser]
./components/Show.tsx [Server Component]
./app/layout.tsx [Server Component]
Client Component SSR:
./lib/secret.ts [Client Component SSR]
./components/Show.tsx [Client Component SSR]
./components/Show.tsx [Server Component]
./app/layout.tsx [Server Component]
at ignore-listed frames
exit=1
빌드가 오류 둘로 멈췄습니다. 둘 다 ./lib/secret.ts:1:1, 곧 import 'server-only'; 줄을 가리킵니다. 둘째 오류가 까닭을 바로 말합니다. server-only를 단 파일은 클라이언트 컴포넌트 모듈에서 import할 수 없습니다(cannot be imported). Import traces 아래 줄을 밑에서 위로 읽으면, layout.tsx가 Show.tsx를, Show.tsx가 lib/secret.ts를 끌어온 길입니다. Show.tsx가 [Server Component]와 [Client Component Browser]로 두 번 서는 것은 'use client' 경계를 넘는 자리라서입니다. Client Component SSR 묶음은 같은 길을 한 번 더 적은 것입니다. 첫째 오류는 Pages Router라고 적지만, 이 앱은 App Router라 그 낱말은 맞지 않습니다.
다 봤으면 components/Show.tsx를 1절 판(앱 이름)으로 되돌리고 lib/secret.ts를 지웁니다.
예제
NEXT_PUBLIC_ 값은 언제 정해질까요? npm run build를 다시 돌려 빌드가 끝나면, .env.local의 앱 이름을 보관함2로 바꿔 저장합니다. 다시 빌드하지 않고 npm run start만 띄워 /stats를 엽니다. 바닥글에는 어느 이름이 보일까요? 고른 뒤 펼쳐 보세요. 맞혀 보기는 점수에 들지 않습니다.
- ①
앱: 보관함2— start가.env.local을 새로 읽는다 - ②
앱: undefined— 배포 판은.env.local을 읽지 않는다 - ③
앱: 보관함— 빌드 때의 이름 그대로다
결과 보기
③입니다. 아래는 1절의 .env.local과 Show · 루트 레이아웃, 빌드 출력, 바꾼 .env.local, 배포 판 화면입니다. 시간은 다를 수 있습니다.
SECRET_KEY=abc123
NEXT_PUBLIC_APP_NAME=보관함
'use client';
function Show() {
const name =
process.env
.NEXT_PUBLIC_APP_NAME;
return <p>{`앱: ${name}`}</p>;
}
export default Show;import type {
Metadata,
} from 'next';
import Image from 'next/image';
import {
Noto_Sans_KR,
} from 'next/font/google';
import './globals.css';
import TabBar from
'@/components/TabBar';
import Show from
'@/components/Show';
const noto = Noto_Sans_KR({
subsets: ['latin'],
});
export const
metadata: Metadata = {
title: {
template:
'%s · 레시피 보관함',
default: '레시피 보관함',
},
description:
'내 레시피를 모아 두는 곳',
};
function RootLayout({
children,
}: LayoutProps<'/'>) {
return (
<html lang="ko">
<body
className={
noto.className
}
>
<TabBar />
{children}
<footer>
바닥글
<Show />
<Image
src="/next.svg"
alt="Next.js"
width={100}
height={20}
/>
</footer>
</body>
</html>
);
}
export default RootLayout; Creating an optimized production build ...
✓ Compiled successfully in 2.1s
Running TypeScript ...
Finished TypeScript in 1025ms ...
Collecting page data using 11 workers ...
레시피 파일 읽음
✓ Collecting page data using 11 workers in 296ms
Generating static pages using 11 workers (0/14) ...
레시피 하나 읽음 r2
레시피 파일 읽음
레시피 하나 읽음 r1
Generating static pages using 11 workers (3/14)
Generating static pages using 11 workers (6/14)
레시피 하나 읽음 r3
레시피 하나 읽음 r4
더하기 쪽을 그림
더하기 쪽을 그림
Generating static pages using 11 workers (10/14)
✓ Generating static pages using 11 workers (14/14) in 414ms
Finalizing page optimization ...
✓ Finalizing page optimization in 10ms
Route (app) Revalidate Expire
┌ ◐ / 1h 1d
├ ○ /_not-found
├ ƒ /api/recipes
├ ◐ /boom
├ ◐ /recipes
├ /recipes/[id]
│ ├ ◐ /recipes/[id]
│ ├ ○ /recipes/r1 1h 1d
│ ├ ○ /recipes/r2 1h 1d
│ └ ◐ [+2 more paths]
├ ○ /recipes/new
└ ○ /stats 1h 1d
ƒ Proxy (Middleware)
○ (Static) prerendered as static content
◐ (Partial Prerender) prerendered as static HTML with dynamic server-streamed content
ƒ (Dynamic) server-rendered on demand
SECRET_KEY=abc123
NEXT_PUBLIC_APP_NAME=보관함2
<nav><a href="/recipes">목록</a>·<a href="/stats">▸ 통계</a></nav><h1>통계</h1><p>모두 4개</p><footer>바닥글<p>앱: 보관함</p><img alt="Next.js" loading="lazy" width="100" height="20" decoding="async" data-nimg="1" src="/next.svg"></footer>NEXT_PUBLIC_ 값은 빌드 때 브라우저로 가는 JS 묶음에 글로 박힙니다(Next.js 문서 Environment Variables — 'can "inline" a value, at build time, into the js bundle'). 그래서 빌드한 뒤 값을 바꿔도 배포 판은 옛 이름을 그립니다(같은 문서 — 'After being built, your app will no longer respond to changes to these environment variables'). 새 이름을 쓰려면 npm run build부터 다시 돌립니다.
빌드한 .next/static/chunks/에는 JS 파일이 여럿 있고, 그 가운데 한 파일에 "앱: 보관함" 글이 있습니다. 터미널에서 grep -rl 보관함 .next/static(윈도는 Git Bash)을 치면 그 파일 이름이 찍힙니다. 편집기의 '모든 파일에서 찾기'는 .gitignore에 든 .next를 건너뛰어 찾지 못합니다.
npm run start도 띄울 때 .env.local을 읽습니다(②가 아님). 배포 서버 배너에 - Environments: 줄이 없는 것은 그 줄을 개발 서버와 빌드만 찍기 때문입니다. start가 새로 읽은 이름이 바닥글에 안 보이는 것은, NEXT_PUBLIC_ 값이 그보다 먼저 빌드 때 묶음에 박혔기 때문입니다(①이 아님).
개발 서버는 다릅니다. .env.local을 저장하면 터미널에 Reload env: .env.local을 찍고 그 줄이 선 뒤의 요청부터 새 값을 씁니다.
다 봤으면 .env.local의 앱 이름을 보관함으로 되돌리고, Ctrl+C로 끈 뒤 npm run dev로 다시 띄웁니다.
자주 틀리는 곳
틀린 생각: 비밀 값은 클라이언트 컴포넌트에서 읽어도 브라우저에서는 비니까 안전하다.
맞는 규칙: 클라이언트 컴포넌트도 첫 방문에는 서버가 그려 HTML로 보냅니다. 그때 읽은 비밀 값이 받은 HTML에 그대로 실립니다(2절). 비밀 값은 서버 컴포넌트 · 서버 함수 · 경로 처리기처럼 서버에서만 도는 코드에서 읽고, 읽는 파일에는 import 'server-only';를 둡니다. 서버 컴포넌트가 읽은 값도 그려 넣거나 클라이언트 컴포넌트에 props로 넘기면 받은 HTML에 실립니다(경계를 넘는 props — 넘긴 값은 글로 바뀌어 쪽과 함께 갑니다). 비밀 키는 바깥 서비스에 요청을 보낼 때처럼 서버 안에서만 쓰고, 화면에 그리거나 넘기지 않습니다(Next.js 문서 Data Security — 'it's possible to accidentally expose private data through how data is fetched or passed to components').
틀린 생각: 비밀 키에도 NEXT_PUBLIC_을 붙이면 어디서나 편하게 읽는다.
맞는 규칙: NEXT_PUBLIC_ 값은 빌드 때 브라우저로 가는 JS 묶음에 글로 박힙니다(예제). 그 묶음은 누구나 내려받으니, 비밀 값에는 붙이지 않습니다.
틀린 생각: .env.local도 코드와 함께 git에 올려 둔다.
맞는 규칙: 비밀 값이 든 파일은 올리지 않습니다. 템플릿의 .gitignore가 .env*를 막아 두었습니다(Next.js 문서 Environment Variables — 'You almost never want to commit these files to your repository').
확인 문제
문제 1. .env.local에 SHOP_KEY=xyz789가 있습니다. 클라이언트 컴포넌트 Badge가 process.env.SHOP_KEY를 읽어 가게: 값 꼴로 그립니다. 첫 방문에 받은 HTML에는 무엇이 들까요?
- ①
가게: undefined - ②
가게: xyz789 - ③
가게:뒤가 빈 글
정답
②입니다. 클라이언트 컴포넌트도 첫 방문에는 서버가 그리고, 서버에는 SHOP_KEY가 있습니다(2절). 비밀 값이 받은 HTML에 실립니다.
- ①
undefined는 브라우저에서 다시 그릴 때의 값입니다. - ③ 서버는
.env.local의 값을 읽습니다. 빈 글이 되지 않습니다.
문제 2. 배포 판의 바닥글에 새 앱 이름이 보이게 하려고 .env.local의 NEXT_PUBLIC_APP_NAME을 바꿨습니다. 그다음 할 일은 무엇일까요?
- ①
npm run start만 다시 띄운다 - ② 브라우저에서 새로 고친다
- ③
npm run build부터 다시 돌린다
정답
③입니다. NEXT_PUBLIC_ 값은 빌드 때 묶음에 박혀, 빌드를 다시 해야 바뀝니다(예제).
- ① start만 다시 띄우면 옛 빌드의 이름이 그대로입니다.
- ② 새로 고쳐도 서버가 보내는 것은 같은 빌드의 묶음입니다.
문제 3. 맨 위에 import 'server-only';가 있는 lib/secret.ts를 클라이언트 컴포넌트가 import하면 어떻게 될까요?
- ①
npm run build가 오류로 멈춘다 - ② 빌드는 되고, 브라우저에서 그 값만
undefined가 된다 - ③ 그 컴포넌트를 서버에서만 그린다
정답
①입니다. 클라이언트 컴포넌트 모듈은 server-only를 단 파일을 끌어올 수 없어 빌드가 멈춥니다(해 보기).
- ②
server-only는 값을 비우는 것이 아니라 빌드를 막습니다. - ③
'use client'파일은 그대로 클라이언트 컴포넌트입니다. 어디서 도는지는 바뀌지 않습니다.
이 레슨에서 바꾼 파일
.env.local — 비밀 키 · 앱 이름(새 파일 · 프로젝트 뿌리 · git에 올리지 않음)
SECRET_KEY=abc123
NEXT_PUBLIC_APP_NAME=보관함
components/Show.tsx — 앱 이름 찍기(새 파일 · 단원 9에서 지움)
'use client';
function Show() {
const name =
process.env
.NEXT_PUBLIC_APP_NAME;
return <p>{`앱: ${name}`}</p>;
}
export default Show;app/layout.tsx — 바닥글에 <Show />
import type {
Metadata,
} from 'next';
import Image from 'next/image';
import {
Noto_Sans_KR,
} from 'next/font/google';
import './globals.css';
import TabBar from
'@/components/TabBar';
import Show from
'@/components/Show';
const noto = Noto_Sans_KR({
subsets: ['latin'],
});
export const
metadata: Metadata = {
title: {
template:
'%s · 레시피 보관함',
default: '레시피 보관함',
},
description:
'내 레시피를 모아 두는 곳',
};
function RootLayout({
children,
}: LayoutProps<'/'>) {
return (
<html lang="ko">
<body
className={
noto.className
}
>
<TabBar />
{children}
<footer>
바닥글
<Show />
<Image
src="/next.svg"
alt="Next.js"
width={100}
height={20}
/>
</footer>
</body>
</html>
);
}
export default RootLayout;이 단원 끝 파일
단원 8에서 바꾼 파일을 모두 끝 판으로 모았습니다. 건너뛴 레슨이 있으면 이 다섯을 붙여 넣고 다음 단원으로 갑니다.
app/api/recipes/route.ts — 백업 내보내기
import {
readFile,
} from 'node:fs/promises';
// 받는 쪽이 파일로 저장하게
const headers = {
'Content-Disposition':
'attachment; filename=' +
'"recipes.json"',
};
export async function GET() {
const text = await readFile(
'data/recipes.json',
'utf8',
);
return Response.json(
JSON.parse(text),
{ headers },
);
}proxy.ts — 옛 주소 /list를 /recipes로 보냄(프로젝트 뿌리)
import {
NextResponse,
type NextRequest,
} from 'next/server';
export function proxy(
request: NextRequest,
) {
return NextResponse.redirect(
new URL(
'/recipes',
request.url,
),
);
}
export const config = {
matcher: '/list',
};.env.local — 비밀 키 · 앱 이름(프로젝트 뿌리 · git에 올리지 않음)
SECRET_KEY=abc123
NEXT_PUBLIC_APP_NAME=보관함components/Show.tsx — 앱 이름 찍기(단원 9에서 지움)
'use client';
function Show() {
const name =
process.env
.NEXT_PUBLIC_APP_NAME;
return <p>{`앱: ${name}`}</p>;
}
export default Show;app/layout.tsx — 바닥글에 <Show />
import type {
Metadata,
} from 'next';
import Image from 'next/image';
import {
Noto_Sans_KR,
} from 'next/font/google';
import './globals.css';
import TabBar from
'@/components/TabBar';
import Show from
'@/components/Show';
const noto = Noto_Sans_KR({
subsets: ['latin'],
});
export const
metadata: Metadata = {
title: {
template:
'%s · 레시피 보관함',
default: '레시피 보관함',
},
description:
'내 레시피를 모아 두는 곳',
};
function RootLayout({
children,
}: LayoutProps<'/'>) {
return (
<html lang="ko">
<body
className={
noto.className
}
>
<TabBar />
{children}
<footer>
바닥글
<Show />
<Image
src="/next.svg"
alt="Next.js"
width={100}
height={20}
/>
</footer>
</body>
</html>
);
}
export default RootLayout;