๐ NextJS
React
+Express.js
+React-Route_Dom
+Server Side Rendering
์ ๋๋
์ค์น
1
npx create-next-app@latest .
์คํ ๋ช ๋ น์ด
๊ฐ๋ฐ : npm run dev
๋ฐฐํฌ : npm run build
์๋น์ค ์์ : npm run start
Route
์ฌ์ฉ์๊ฐ ์ ์ํ๋ ๊ฒฝ๋ก์ ์ฐ๋ฆฌ๊ฐ ์ค์ ํ๋ ๊ฒฝ๋ก์ ์ฃผ์์ฐจ์ด
http://a.com/ => /pages/index.tsx
http://a.com.sub/ => /pages/sub/index.tsx
http://a.com/sub/about => /pages/sub/about.tsx
http://a.com/sub/1 => /pages/sub/[id].tsx
http://a.com/sub/2 => /pages/sub/[id].tsx
[id] ํ๋ผ๋ฏธํฐ๋ฅผ ๋ฐ๋๋ฒ
useRouter๋ฅผ ์ด์ฉํ์ฌ ํ๋ผ๋ฏธํฐ๋ฅผ ๋ฐ๊ณ ํ๋ฉด์ ํ์ํด์ค๋ค
API Route
next์ ํน์ง์ค ํ๋๋ SSR๊ณผ CSR์ ๋ชจ๋ ๊ฐ์ง๊ณ ์๋ ์ฌ์ธ์ ์๋ฃจ์
http://a.com/api => /pages/api/index.tsx
์๋ฒ์ a.com/api๋ก ๋ฐ์ดํฐ ์์ฒญ ํ pages/api/index.tsx์ ๋ฐ์ดํฐ๋ฅผ ์๋ฒ์ชฝ์์ ๊ณต๊ธํ๋๋ก ํ ์์์
/api ์๋์ [id].ts๋ก ์์ ์์ฑ
1
2
3
4
5
import type { NextApiRequest, NextApiResponse } from "next";
export default function handler(req: NextApiRequest, res: NextApiResponse) {
res.status(200).json({ id: req.query.id });
}
/api/1 ๋ก ์ด๋์
{โidโ:โ1โ}
์ด ํ์ด์ง์ ๋์จ๋ค
env ํ๊ฒฝ๋ณ์
๋ณดํต์ ๊ฒฝ์ฐ
.env ํ์ผ ์์
API_URL=http://localhost:3000/
์ด๋ฐ์์ผ๋ก ์ฐ์ง๋ง
next์ ๊ฒฝ์ฐ
API_URL ์์ NEXT_PUBLIC์ ๋ถ์ด์ผ ํ๋ค.
NEXT_PUBLIC_API_URL
์ด๋ ๊ฒํ๋ฉด ๋น๋์ ๋ฐฐํฌํ์ผ์ ํฌํจ๋๋ค.
.env ํ์ผ
1
NEXT_PUBLIC_API_URL=http://localhost:3000/
/pages/index.tsx ์์ ์ถ๊ฐ
1
2
3
<li>
<Link href="/sub/fetch">/pages/sub/fetch.js</Link>
</li>
/sub/fetch.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import Link from "next/link";
import React, { useEffect } from "react";
const Fetch = () => {
useEffect(() => {
fetch(process.env.NEXT_PUBLIC_API_URL + "api/1")
.then((res) => res.json())
.then((data) => console.log(data));
});
return (
<>
<h1>/page/sub/fetch.js</h1>
<Link href="/">/pages/index.js</Link>
</>
);
};
export default Fetch;