Home NextJS
Post
Cancel

NextJS

๐Ÿ“Œ 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

image

image

[id] ํŒŒ๋ผ๋ฏธํ„ฐ๋ฅผ ๋ฐ›๋Š”๋ฒ•

image

useRouter๋ฅผ ์ด์šฉํ•˜์—ฌ ํŒŒ๋ผ๋ฏธํ„ฐ๋ฅผ ๋ฐ›๊ณ  ํ™”๋ฉด์— ํ‘œ์‹œํ•ด์ค€๋‹ค

image

image

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;

image

This post is licensed under CC BY 4.0 by the author.