Ver3.0 ๐ ํ์ ์คํฌ๋ฆฝํธ๋ก ์์ฑํ๋ ์๋ฒ์ฌ์ด๋ ๋ ๋๋ง: Next.js ํ์ ์์คํ ์ต์ ํ ์๋ฒฝ ๊ฐ์ด๋

๐ ํ์ ์คํฌ๋ฆฝํธ๋ก ์์ฑํ๋ ์๋ฒ์ฌ์ด๋ ๋ ๋๋ง: Next.js ํ์ ์์คํ ์ต์ ํ ์๋ฒฝ ๊ฐ์ด๋
SSR๊ณผ ํ์ ์์ ์ฑ, ๋ ๋ง๋ฆฌ ํ ๋ผ๋ฅผ ํ ๋ฒ์ ์ก๋ ์ค์ ๋ ธํ์ฐ
๐ฌ ์ ํ์ ์คํฌ๋ฆฝํธ์ SSR์ ํจ๊ป ์จ์ผ ํ ๊น?
์, ๋จผ์ ์์งํ๊ฒ ์๊ธฐํด๋ณด์. ๋๋ ์๋ค์ํผ ์์ฆ ์น ๊ฐ๋ฐ ํธ๋ ๋๋ ์์ ํ ๋ฐ๋์์ด. ์์ ์ฒ๋ผ ๋จ์ํ "์๋๋ง ํ๋ฉด ๋ผ!"๋ผ๋ ์๋๋ ์ง๋ฌ์ง. ์ฌ์ฉ์๋ค์ ๋น ๋ฅธ ์ด๊ธฐ ๋ก๋ฉ์ ์ํ๊ณ , ๊ฒ์ ์์ง์ ์ ๋๋ก ๋ SEO๋ฅผ ์๊ตฌํ๊ณ , ๊ฐ๋ฐํ์ ์ ์ง๋ณด์ ๊ฐ๋ฅํ ์ฝ๋๋ฅผ ์ํด. ์ด ๋ชจ๋ ๊ฑธ ํ ๋ฒ์ ํด๊ฒฐํ๋ ๊ฒ ๋ฐ๋ก ํ์ ์คํฌ๋ฆฝํธ + Next.js SSR ์กฐํฉ์ด์ผ! ๐ํ์ ์คํฌ๋ฆฝํธ๋ ์๋ฐ์คํฌ๋ฆฝํธ์ ํ์ ์์คํ ์ ๋ํ ๊ฑฐ์์? ์ด๊ฒ ์ ์ค์ํ๋๋ฉด, ์๋ฒ์ฌ์ด๋ ๋ ๋๋ง ํ๊ฒฝ์์๋ ํด๋ผ์ด์ธํธ์ ์๋ฒ ์์ชฝ์์ ์ฝ๋๊ฐ ์คํ๋๊ธฐ ๋๋ฌธ์ ํ์ ์์ ์ฑ์ด ๋์ฑ ์ค์ํด์ ธ. ์๋ฒ์์ ๋ฐ์ดํฐ๋ฅผ ๊ฐ์ ธ์์ ํด๋ผ์ด์ธํธ๋ก ์ ๋ฌํ๋ ๊ณผ์ ์์ ํ์ ์ด ๋ง์ง ์์ผ๋ฉด? ๋ฐํ์ ์๋ฌ๊ฐ ํฐ์ง๋ ๊ฑด ์๊ฐ๋ฌธ์ ์ผ. ๐ฅ
Next.js๋ ๋ฆฌ์กํธ ๊ธฐ๋ฐ์ ํ๋ ์์ํฌ์ธ๋ฐ, SSR์ ์ ๋ง ์ฝ๊ฒ ๊ตฌํํ ์ ์๊ฒ ํด์ค. ๊ทธ๋ฅ ํ์ผ ํ๋ ๋ง๋ค๋ฉด ์๋์ผ๋ก ๋ผ์ฐํ ๋ ๋๊ณ , `getServerSideProps`๋ `getStaticProps` ๊ฐ์ ํจ์๋ง exportํ๋ฉด ์๋ฒ์ฌ์ด๋ ๋ ๋๋ง์ด ๋๋ฑ ์์ฑ๋ผ. ์ฌ๊ธฐ์ ํ์ ์คํฌ๋ฆฝํธ๋ฅผ ์น์ผ๋ฉด? ์๋ฒฝํ ํ์ ์ถ๋ก ๊ณผ ์๋์์ฑ๊น์ง ๋ค์ผ๋ก ์ป๋ ๊ฑฐ์ง! ๐
โ๏ธ Next.js์์ ํ์ ์คํฌ๋ฆฝํธ ์ธํ ํ๊ธฐ
์ข์, ์ด์ ๋ณธ๊ฒฉ์ ์ผ๋ก ์์ํด๋ณด์! Next.js ํ๋ก์ ํธ์ ํ์ ์คํฌ๋ฆฝํธ๋ฅผ ์ธํ ํ๋ ๊ฑด ์๊ฐ๋ณด๋ค ํจ์ฌ ๊ฐ๋จํด. Next.js ํ์ด ํ์ ์คํฌ๋ฆฝํธ๋ฅผ 1๊ธ ์๋ฏผ(first-class citizen)์ผ๋ก ๋์ฐํ๊ฑฐ๋ . ๐npx create-next-app@latest my-app --typescript
cd my-app
npm run dev
๋! ์ด๊ฒ ๋ค์ผ. Next.js๊ฐ ์์์ `tsconfig.json` ํ์ผ์ ์์ฑํ๊ณ , ํ์ํ ํ์
์ ์ ํ์ผ๋ค๋ ์ค์นํด์ค. ์ ๋ง ์น์ ํ์ง? ๐๋ง์ฝ ๊ธฐ์กด ํ๋ก์ ํธ์ ํ์ ์คํฌ๋ฆฝํธ๋ฅผ ์ถ๊ฐํ๊ณ ์ถ๋ค๋ฉด:
npm install --save-dev typescript @types/react @types/node
touch tsconfig.json
npm run dev
๊ฐ๋ฐ ์๋ฒ๋ฅผ ์คํํ๋ฉด Next.js๊ฐ ์๋์ผ๋ก `tsconfig.json`์ ์ฑ์์ค. ์ด๊ฒ Next.js์ ๋ง๋ฒ์ด์ผ! โจโข strict: true - ์๊ฒฉํ ํ์ ์ฒดํฌ ํ์ฑํ (๊ฐ๋ ฅ ์ถ์ฒ!)
โข noImplicitAny: true - any ํ์ ์๋ฌต์ ์ฌ์ฉ ๊ธ์ง
โข strictNullChecks: true - null/undefined ์ฒดํฌ ๊ฐํ
โข esModuleInterop: true - CommonJS ๋ชจ๋ ํธํ์ฑ
โข jsx: "preserve" - Next.js๊ฐ JSX ๋ณํ ์ฒ๋ฆฌ
์ด ์ค์ ๋ค์ด ํ์ ์์ ์ฑ์ ๊ธฐ์ด๋ฅผ ๋ง๋ค์ด์ค! ๐๏ธ
๐จ ํ์ด์ง ์ปดํฌ๋ํธ ํ์ ์ ์ํ๊ธฐ
์, ์ด์ ์ค์ ์ด์ผ! Next.js์์ ํ์ด์ง๋ฅผ ๋ง๋ค ๋ ํ์ ์ ์ด๋ป๊ฒ ์ ์ํ๋์ง ์์๋ณด์. ํ์ด์ง ์ปดํฌ๋ํธ๋ ํฌ๊ฒ ๋ ๊ฐ์ง ๋ฐฉ์์ผ๋ก ํ์ ์ ์ ์ํ ์ ์์ด.1. ๊ธฐ๋ณธ ํ์ด์ง ์ปดํฌ๋ํธ ํ์
๊ฐ์ฅ ๊ฐ๋จํ ํ์ด์ง๋ถํฐ ์์ํด๋ณผ๊น:
import type { NextPage } from 'next'
const Home: NextPage = () => {
return (
<div>
<h1>์๋
ํ์ธ์! ํ์
์์ ํ ํ์ด์ง์
๋๋ค ๐</h1>
</div>
)
}
export default Home
`NextPage` ํ์
์ ์ฌ์ฉํ๋ฉด Next.js ํ์ด์ง ์ปดํฌ๋ํธ์ ๊ธฐ๋ณธ ํ์
์ด ์๋์ผ๋ก ์ ์ฉ๋ผ. ๊ฐ๋จํ์ง? ๐2. Props๋ฅผ ๋ฐ๋ ํ์ด์ง ์ปดํฌ๋ํธ
์ค์ ๋ก๋ ๋๋ถ๋ถ ์๋ฒ์์ ๋ฐ์ดํฐ๋ฅผ ๋ฐ์์์ props๋ก ์ ๋ฌํ์์? ์ด๋ด ๋๋ ์ ๋ค๋ฆญ์ ์ฌ์ฉํด:
import type { NextPage } from 'next'
interface UserData {
id: number
name: string
email: string
createdAt: string
}
interface HomeProps {
users: UserData[]
totalCount: number
}
const Home: NextPage<HomeProps> = ({ users, totalCount }) => {
return (
<div>
<h1>์ ์ฒด ์ฌ์ฉ์: {totalCount}๋ช
</h1>
{users.map(user => (
<div key={user.id}>
<p>{user.name} ({user.email})</p>
</div>
))}
</div>
)
}
export default Home
์ด๋ ๊ฒ ํ๋ฉด `users`์ `totalCount`์ ํ์
์ด ๋ช
ํํ๊ฒ ์ ์๋ผ์, ์ปดํฌ๋ํธ ๋ด๋ถ์์ ์๋์์ฑ๋ ๋๊ณ ํ์
์ฒดํฌ๋ ์๋ฒฝํ๊ฒ ๋ผ! ๐ฏ๐ getServerSideProps ํ์ ์ต์ ํ
์, ์ด์ ์ง์ง ํต์ฌ์ผ๋ก ๋ค์ด๊ฐ๋ณด์! SSR์ ๊ฝ์ด๋ผ๊ณ ํ ์ ์๋ `getServerSideProps`์ ํ์ ์ ์์ผ. ์ด๊ฒ ์ ๋๋ก ์ ๋๋ฉด ์๋ฒ์ ํด๋ผ์ด์ธํธ ์ฌ์ด์์ ํ์ ๋ถ์ผ์น๊ฐ ๋ฐ์ํ ์ ์์ด. ๐ฑ๊ธฐ๋ณธ ํ์ ์ ์
Next.js๋ `GetServerSideProps` ํ์ ์ ์ ๊ณตํด์ค:
import type { GetServerSideProps, NextPage } from 'next'
interface Product {
id: string
name: string
price: number
description: string
inStock: boolean
}
interface ProductPageProps {
product: Product
relatedProducts: Product[]
}
export const getServerSideProps: GetServerSideProps<ProductPageProps> = async (context) => {
const { id } = context.params as { id: string }
// API ํธ์ถ
const productRes = await fetch(`https://api.example.com/products/${id}`)
const product: Product = await productRes.json()
const relatedRes = await fetch(`https://api.example.com/products/${id}/related`)
const relatedProducts: Product[] = await relatedRes.json()
return {
props: {
product,
relatedProducts
}
}
}
const ProductPage: NextPage<ProductPageProps> = ({ product, relatedProducts }) => {
return (
<div>
<h1>{product.name}</h1>
<p>๊ฐ๊ฒฉ: {product.price.toLocaleString()}์</p>
<p>{product.inStock ? '์ฌ๊ณ ์์ โ
' : 'ํ์ โ'}</p>
</div>
)
}
์ฌ๊ธฐ์ ์ค์ํ ํฌ์ธํธ๋ `GetServerSidePropsโข props ์คํ ๋ฐ์ ๊ฐ๋ฅ (product.nam ๊ฐ์ ์ค์)
โข ๋ฐํ์์์์ผ ์๋ฌ ๋ฐ๊ฒฌ
โข ์๋์์ฑ ์์
โข ๋ฆฌํฉํ ๋ง ์ ๋๋ฝ ๊ฐ๋ฅ
ํ์ ์ ์ ํ:
โข ์ปดํ์ผ ํ์์ ์๋ฌ ๊ฒ์ถ โ
โข IDE ์๋์์ฑ ์ง์ โ
โข ์์ ํ ๋ฆฌํฉํ ๋ง โ
โข ์ฝ๋ ๊ฐ๋ ์ฑ ํฅ์ โ
์ค์ ์์๋ ์๋ฌ ์ฒ๋ฆฌ๋ ์ค์ํ์ง. `getServerSideProps`๋ ์ฌ๋ฌ ๊ฐ์ง ๋ฐํ ํ์ ์ ์ง์ํด:
export const getServerSideProps: GetServerSideProps<ProductPageProps> = async (context) => {
try {
const { id } = context.params as { id: string }
const res = await fetch(`https://api.example.com/products/${id}`)
// 404 ์ฒ๋ฆฌ
if (!res.ok) {
return {
notFound: true // ํ์
์์ ํ 404 ๋ฐํ
}
}
const product: Product = await res.json()
// ์กฐ๊ฑด๋ถ ๋ฆฌ๋ค์ด๋ ํธ
if (!product.inStock) {
return {
redirect: {
destination: '/out-of-stock',
permanent: false
}
}
}
return {
props: { product, relatedProducts: [] }
}
} catch (error) {
console.error('๋ฐ์ดํฐ ๋ก๋ฉ ์คํจ:', error)
return {
notFound: true
}
}
}
`notFound`์ `redirect`๋ ๋ชจ๋ ํ์
์ด ์ ์๋์ด ์์ด์ ์์ ํ๊ฒ ์ฌ์ฉํ ์ ์์ด! ๐`context` ๊ฐ์ฒด์๋ `params`, `query`, `req`, `res` ๋ฑ ๋ค์ํ ์ ๋ณด๊ฐ ๋ค์ด์์ด. ์ด๊ฒ๋ค๋ ํ์ ์ด ์ ์๋์ด ์์ผ๋๊น ์ ๊ทน ํ์ฉํด๋ด:
export const getServerSideProps: GetServerSideProps = async (context) => {
const { req, res, query, params } = context
// ์ฟ ํค ์ ๊ทผ (ํ์
์์ )
const cookies = req.cookies
// ์ฟผ๋ฆฌ ํ๋ผ๋ฏธํฐ (ํ์
์บ์คํ
ํ์)
const page = Number(query.page) || 1
// ์ปค์คํ
ํค๋ ์ค์
res.setHeader('Cache-Control', 'public, s-maxage=10, stale-while-revalidate=59')
// ...
}
๐ฆ getStaticProps์ getStaticPaths ํ์ ์ ์
SSG(Static Site Generation)๋ฅผ ์ฌ์ฉํ ๋๋ `getStaticProps`์ `getStaticPaths`๋ฅผ ์ฐ์ง? ์ด๊ฒ๋ค๋ ํ์ ์ ์๊ฐ ์ค์ํด! ํนํ ๋์ ๋ผ์ฐํ ์ ์ฌ์ฉํ ๋๋ ๋๋์ฑ ๊ทธ๋. ๐ฏgetStaticProps ๊ธฐ๋ณธ ํ์
import type { GetStaticProps, NextPage } from 'next'
interface BlogPost {
id: string
title: string
content: string
author: string
publishedAt: string
tags: string[]
}
interface BlogPageProps {
posts: BlogPost[]
totalPages: number
}
export const getStaticProps: GetStaticProps<BlogPageProps> = async () => {
const res = await fetch('https://api.example.com/posts')
const posts: BlogPost[] = await res.json()
return {
props: {
posts,
totalPages: Math.ceil(posts.length / 10)
},
revalidate: 60 // ISR: 60์ด๋ง๋ค ์ฌ์์ฑ
}
}
const BlogPage: NextPage<BlogPageProps> = ({ posts, totalPages }) => {
return (
<div>
<h1>๋ธ๋ก๊ทธ ํฌ์คํธ ๐</h1>
{posts.map(post => (
<article key={post.id}>
<h2>{post.title}</h2>
<p>์์ฑ์: {post.author}</p>
</article>
))}
</div>
)
}
`getStaticProps`๋ ๋น๋ ํ์์ ์คํ๋๊ธฐ ๋๋ฌธ์ `context` ๊ฐ์ฒด๊ฐ `getServerSideProps`๋ณด๋ค ์ ํ์ ์ด์ผ. ํ์ง๋ง ํ์
์ ์ ๋ฐฉ์์ ๊ฑฐ์ ๋์ผํด! ๐getStaticPaths ํ์ ์ ์
๋์ ๋ผ์ฐํ ์ ์ฌ์ฉํ ๋๋ `getStaticPaths`๊ฐ ํ์์ผ. ์ด๊ฒ๋ ํ์ ์ ์ ๋๋ก ์ ์ํด์ผ ํด:
import type { GetStaticPaths, GetStaticProps } from 'next'
interface PostParams {
slug: string
}
interface PostProps {
post: BlogPost
}
export const getStaticPaths: GetStaticPaths<PostParams> = async () => {
const res = await fetch('https://api.example.com/posts')
const posts: BlogPost[] = await res.json()
const paths = posts.map(post => ({
params: { slug: post.id }
}))
return {
paths,
fallback: 'blocking' // ๋๋ true, false
}
}
export const getStaticProps: GetStaticProps<PostProps, PostParams> = async (context) => {
const { slug } = context.params! // params๋ ํญ์ ์กด์ฌ
const res = await fetch(`https://api.example.com/posts/${slug}`)
const post: BlogPost = await res.json()
return {
props: { post },
revalidate: 3600 // 1์๊ฐ๋ง๋ค ์ฌ์์ฑ
}
}
์ฌ๊ธฐ์ ์ฃผ๋ชฉํ ์ ์ `GetStaticProps- paths์ ์๋ ๊ฒฝ๋ก๋ 404
- ๊ฐ์ฅ ๊ฐ๋จํ ํ์ ์ฒ๋ฆฌ
โข fallback: true
- ์ปดํฌ๋ํธ์์ ๋ก๋ฉ ์ํ ์ฒ๋ฆฌ ํ์
- props๊ฐ undefined์ผ ์ ์์
- ํ์ ๊ฐ๋ ํ์!
โข fallback: 'blocking'
- SSR์ฒ๋ผ ๋์
- props๋ ํญ์ ์กด์ฌ
- ํ์ ์ฒ๋ฆฌ๊ฐ ๊ฐ์ฅ ๊น๋ํจ โ
import { useRouter } from 'next/router'
const PostPage: NextPage<PostProps> = ({ post }) => {
const router = useRouter()
// fallback ์ํ ์ฒดํฌ
if (router.isFallback) {
return <div>๋ก๋ฉ ์ค... โณ</div>
}
// ์ด์ post๋ ํ์คํ ์กด์ฌ
return (
<article>
<h1>{post.title}</h1>
<p>{post.content}</p>
</article>
)
}
๐ญ API ๋ผ์ฐํธ ํ์ ์ ์
Next.js์ API ๋ผ์ฐํธ๋ ํ์ ์ ์๊ฐ ๊ฐ๋ฅํด! ๋ฐฑ์๋ API๋ฅผ ๋ง๋ค ๋ ํ์ ์์ ์ฑ์ ํ๋ณดํ๋ ๊ฑด ์ ๋ง ์ค์ํ๊ฑฐ๋ . ๐๊ธฐ๋ณธ API ํธ๋ค๋ฌ ํ์
import type { NextApiRequest, NextApiResponse } from 'next'
interface UserResponse {
id: string
name: string
email: string
}
interface ErrorResponse {
error: string
message: string
}
export default async function handler(
req: NextApiRequest,
res: NextApiResponse<UserResponse | ErrorResponse>
) {
if (req.method !== 'GET') {
return res.status(405).json({
error: 'Method Not Allowed',
message: 'GET ์์ฒญ๋ง ํ์ฉ๋ฉ๋๋ค'
})
}
try {
const { id } = req.query
if (!id || typeof id !== 'string') {
return res.status(400).json({
error: 'Bad Request',
message: 'ID๊ฐ ํ์ํฉ๋๋ค'
})
}
const user: UserResponse = {
id,
name: 'ํ๊ธธ๋',
email: 'hong@example.com'
}
return res.status(200).json(user)
} catch (error) {
return res.status(500).json({
error: 'Internal Server Error',
message: '์๋ฒ ์ค๋ฅ๊ฐ ๋ฐ์ํ์ต๋๋ค'
})
}
}
`NextApiResponse์ ๋ค๋ฆญ API ํธ๋ค๋ฌ ๋ง๋ค๊ธฐ
์ฌ์ฌ์ฉ ๊ฐ๋ฅํ ํ์ ์ ๋ง๋ค๋ฉด ๋ ํธํด:
type ApiResponse<T> = {
success: true
data: T
} | {
success: false
error: string
message: string
}
interface CreateUserRequest {
name: string
email: string
password: string
}
interface CreateUserData {
id: string
name: string
email: string
createdAt: string
}
export default async function handler(
req: NextApiRequest,
res: NextApiResponse<ApiResponse<CreateUserData>>
) {
if (req.method !== 'POST') {
return res.status(405).json({
success: false,
error: 'Method Not Allowed',
message: 'POST ์์ฒญ๋ง ํ์ฉ๋ฉ๋๋ค'
})
}
try {
const body = req.body as CreateUserRequest
// ์ ํจ์ฑ ๊ฒ์ฌ
if (!body.name || !body.email || !body.password) {
return res.status(400).json({
success: false,
error: 'Validation Error',
message: '๋ชจ๋ ํ๋๋ฅผ ์
๋ ฅํด์ฃผ์ธ์'
})
}
// ์ฌ์ฉ์ ์์ฑ ๋ก์ง...
const newUser: CreateUserData = {
id: 'user_123',
name: body.name,
email: body.email,
createdAt: new Date().toISOString()
}
return res.status(201).json({
success: true,
data: newUser
})
} catch (error) {
return res.status(500).json({
success: false,
error: 'Internal Server Error',
message: '์๋ฒ ์ค๋ฅ๊ฐ ๋ฐ์ํ์ต๋๋ค'
})
}
}
์ด๋ ๊ฒ `ApiResponseAPI ๋ผ์ฐํธ์์ ๋ฏธ๋ค์จ์ด๋ฅผ ์ฌ์ฉํ ๋๋ ํ์ ์ ์ ์ํ ์ ์์ด:
type Middleware = (
req: NextApiRequest,
res: NextApiResponse,
next: () => void
) => void
const authMiddleware: Middleware = (req, res, next) => {
const token = req.headers.authorization
if (!token) {
res.status(401).json({ error: 'Unauthorized' })
return
}
// ํ ํฐ ๊ฒ์ฆ ๋ก์ง...
next()
}
๐ง ๊ณ ๊ธ ํ์ ํจํด๊ณผ ์ต์ ํ ๊ธฐ๋ฒ
์, ์ด์ ์ข ๋ ๊ณ ๊ธ ๊ธฐ๋ฒ๋ค์ ์์๋ณด์! ์ค์ ์์ ์ ๋ง ์ ์ฉํ ํจํด๋ค์ด์ผ. ๐1. ํ์ ์ถ๋ก ํ์ฉํ๊ธฐ
ํ์ ์คํฌ๋ฆฝํธ์ ๊ฐ๋ ฅํ ํ์ ์ถ๋ก ์ ํ์ฉํ๋ฉด ์ฝ๋๊ฐ ํจ์ฌ ๊น๋ํด์ ธ:
// โ ๋ถํ์ํ ํ์
๋ช
์
const getUser = async (id: string): Promise<UserResponse> => {
const res: Response = await fetch(`/api/users/${id}`)
const data: UserResponse = await res.json()
return data
}
// โ
ํ์
์ถ๋ก ํ์ฉ
const getUser = async (id: string) => {
const res = await fetch(`/api/users/${id}`)
const data: UserResponse = await res.json()
return data // ๋ฐํ ํ์
์๋ ์ถ๋ก
}
ํ์ํ ๊ณณ์๋ง ํ์
์ ๋ช
์ํ๊ณ , ๋๋จธ์ง๋ ํ์
์คํฌ๋ฆฝํธ๊ฐ ์์์ ์ถ๋ก ํ๊ฒ ํ๋ ๊ฒ ์ข์! ๐2. ์ ํธ๋ฆฌํฐ ํ์ ํ์ฉ
ํ์ ์คํฌ๋ฆฝํธ์ ์ ํธ๋ฆฌํฐ ํ์ ๋ค์ ์ ๊ทน ํ์ฉํด๋ด:
interface User {
id: string
name: string
email: string
password: string
createdAt: string
updatedAt: string
}
// ๋น๋ฐ๋ฒํธ ์ ์ธํ ๊ณต๊ฐ ์ ๋ณด
type PublicUser = Omit<User, 'password'>
// ์
๋ฐ์ดํธ ๊ฐ๋ฅํ ํ๋๋ง
type UpdateUserInput = Partial<Pick<User, 'name' | 'email'>>
// ์ฝ๊ธฐ ์ ์ฉ ์ฌ์ฉ์
type ReadonlyUser = Readonly<User>
// ํ์ ํ๋๋ง
type RequiredUser = Required<Pick<User, 'id' | 'name' | 'email'>>
์ด๋ฐ ์ ํธ๋ฆฌํฐ ํ์
๋ค์ ์กฐํฉํ๋ฉด ์ ๋ง ๊ฐ๋ ฅํ ํ์
์์คํ
์ ๋ง๋ค ์ ์์ด! ๐จ3. ์กฐ๊ฑด๋ถ ํ์ ์ผ๋ก ์ ์ฐ์ฑ ํ๋ณด
type ApiResult<T, E = Error> =
| { status: 'success'; data: T }
| { status: 'error'; error: E }
| { status: 'loading' }
// ์ฌ์ฉ ์์
const fetchData = async <T>(url: string): Promise<ApiResult<T>> => {
try {
const res = await fetch(url)
const data = await res.json()
return { status: 'success', data }
} catch (error) {
return { status: 'error', error: error as Error }
}
}
// ํ์
๊ฐ๋์ ํจ๊ป ์ฌ์ฉ
const result = await fetchData<User[]>('/api/users')
if (result.status === 'success') {
// result.data๋ User[] ํ์
console.log(result.data.length)
} else if (result.status === 'error') {
// result.error๋ Error ํ์
console.error(result.error.message)
}
์กฐ๊ฑด๋ถ ํ์
๊ณผ ํ์
๊ฐ๋๋ฅผ ์กฐํฉํ๋ฉด ๋ฐํ์ ์์ ์ฑ์ด ํฌ๊ฒ ํฅ์๋ผ! ๐ก๏ธํ๊ฒฝ ๋ณ์๋ ํ์ ์์ ํ๊ฒ ๊ด๋ฆฌํ ์ ์์ด:
// env.d.ts
declare namespace NodeJS {
interface ProcessEnv {
NEXT_PUBLIC_API_URL: string
DATABASE_URL: string
JWT_SECRET: string
NODE_ENV: 'development' | 'production' | 'test'
}
}
// ์ฌ์ฉ
const apiUrl = process.env.NEXT_PUBLIC_API_URL // ํ์
์์ !
const nodeEnv = process.env.NODE_ENV // 'development' | 'production' | 'test'
์ด์ ํ๊ฒฝ ๋ณ์ ์คํ๋ ์ปดํ์ผ ํ์์ ์ก์ ์ ์์ด! ๐
์ฌ์ฌ์ฉ ๊ฐ๋ฅํ ์ ๋ค๋ฆญ ์ปดํฌ๋ํธ๋ฅผ ๋ง๋ค์ด๋ณด์:
interface ListProps<T> {
items: T[]
renderItem: (item: T, index: number) => React.ReactNode
keyExtractor: (item: T) => string
emptyMessage?: string
}
function List<T>({ items, renderItem, keyExtractor, emptyMessage }: ListProps<T>) {
if (items.length === 0) {
return <div>{emptyMessage || 'ํญ๋ชฉ์ด ์์ต๋๋ค'}</div>
}
return (
<div>
{items.map((item, index) => (
<div key={keyExtractor(item)}>
{renderItem(item, index)}
</div>
))}
</div>
)
}
// ์ฌ์ฉ
<List
items={users}
renderItem={(user) => <UserCard user={user} />}
keyExtractor={(user) => user.id}
emptyMessage="์ฌ์ฉ์๊ฐ ์์ต๋๋ค"
/>
์ ๋ค๋ฆญ ์ปดํฌ๋ํธ๋ ํ์
์์ ์ฑ์ ์ ์งํ๋ฉด์๋ ์ฌ์ฌ์ฉ์ฑ์ ๊ทน๋ํํด์ค! ๐โก ์ฑ๋ฅ ์ต์ ํ์ ํ์ ์์คํ
ํ์ ์์คํ ์ด ์ฑ๋ฅ์๋ ์ํฅ์ ์ค ์ ์๋ค๋ ๊ฑฐ ์๊ณ ์์ด? ํนํ ๋๊ท๋ชจ ํ๋ก์ ํธ์์๋ ํ์ ์ฒดํฌ ์๊ฐ์ด ๋น๋ ์๊ฐ์ ํฐ ์ํฅ์ ๋ฏธ์ณ. ์ต์ ํ ๋ฐฉ๋ฒ์ ์์๋ณด์! ๐1. ํ์ ์ํฌํธ ์ต์ ํ
ํ์ ๋ง ์ํฌํธํ ๋๋ `type` ํค์๋๋ฅผ ์ฌ์ฉํด:
// โ ๋ฐํ์ ์ฝ๋๋ ํจ๊ป ๋ฒ๋ค๋ง
import { User, Product } from './types'
// โ
ํ์
๋ง ์ํฌํธ (๋ฒ๋ค ํฌ๊ธฐ ๊ฐ์)
import type { User, Product } from './types'
// ํผํฉ ์ฌ์ฉ
import { fetchUser, type User } from './api'
์ด๋ ๊ฒ ํ๋ฉด ํ์
์ ๋ณด๋ ์ปดํ์ผ ํ์์๋ง ์ฌ์ฉ๋๊ณ ๋ฐํ์ ๋ฒ๋ค์๋ ํฌํจ๋์ง ์์! ๋ฒ๋ค ํฌ๊ธฐ๊ฐ ์ค์ด๋ค์ด. ๐ฆ2. ํ์ ์ฒดํฌ ๋ฒ์ ์ ํ
`tsconfig.json`์์ ๋ถํ์ํ ํ์ผ ์ฒดํฌ๋ฅผ ์ ์ธํด:
{
"compilerOptions": {
"strict": true,
"skipLibCheck": true // node_modules ํ์
์ฒดํฌ ์คํต
},
"include": [
"next-env.d.ts",
"**/*.ts",
"**/*.tsx"
],
"exclude": [
"node_modules",
".next",
"out",
"public"
]
}
`skipLibCheck: true`๋ ์ธ๋ถ ๋ผ์ด๋ธ๋ฌ๋ฆฌ์ ํ์
์ ์ ํ์ผ ์ฒดํฌ๋ฅผ ๊ฑด๋๋ฐ์ด์ ์ปดํ์ผ ์๋๋ฅผ ํฌ๊ฒ ํฅ์์์ผ! โก3. ์ฆ๋ถ ์ปดํ์ผ ํ์ฉ
{
"compilerOptions": {
"incremental": true,
"tsBuildInfoFile": ".tsbuildinfo"
}
}
์ฆ๋ถ ์ปดํ์ผ์ ํ์ฑํํ๋ฉด ๋ณ๊ฒฝ๋ ํ์ผ๋ง ๋ค์ ์ปดํ์ผํด์ ๋น๋ ์๊ฐ์ด ๋จ์ถ๋ผ! ๐ฏ์ฑ๋ฅ์ ์ํด `any` ํ์ ์ ๋จ์ฉํ๋ฉด ์ ๋ผ! ํ์ ์์ ์ฑ์ ์์ผ๋ฉด ๋์ค์ ๋ ํฐ ๋ฌธ์ ๊ฐ ์๊ฒจ. ๋์ `unknown` ํ์ ์ ์ฌ์ฉํ๊ณ ํ์ ๊ฐ๋๋ก ์ขํ๋๊ฐ๋ ๊ฒ ์ข์:
// โ ํ์
์์ ์ฑ ์์ค
const data: any = await fetchData()
// โ
์์ ํ ๋ฐฉ๋ฒ
const data: unknown = await fetchData()
if (isValidData(data)) {
// ์ด์ data๋ ๊ฒ์ฆ๋ ํ์
console.log(data.name)
}
์ฑ๋ฅ ์ฐจ์ด๋ ๋ฏธ๋ฏธํ์ง๋ง, ์ฌ์ฉ ํจํด์ ๋ฐ๋ผ ์ ํํด:
// ์ธํฐํ์ด์ค: ํ์ฅ ๊ฐ๋ฅ, ์ ์ธ ๋ณํฉ ์ง์
interface User {
id: string
name: string
}
interface User { // ์ ์ธ ๋ณํฉ
email: string
}
// ํ์
๋ณ์นญ: ์ ๋์จ, ๊ต์ฐจ ํ์
๋ฑ ๋ณต์กํ ํ์
ํํ
type Status = 'pending' | 'approved' | 'rejected'
type ApiResponse<T> = { data: T } | { error: string }
์ผ๋ฐ์ ์ผ๋ก ๊ฐ์ฒด ํ์
์ ์ธํฐํ์ด์ค, ์ ๋์จ์ด๋ ๋ณต์กํ ํ์
์ ํ์
๋ณ์นญ์ ์ฌ์ฉํ๋ ๊ฒ ์ข์! ๐๐ ์ค์ ๋๋ฒ๊น ๊ณผ ํธ๋ฌ๋ธ์ํ
ํ์ ์๋ฌ๋ฅผ ๋ง๋ฌ์ ๋ ์ด๋ป๊ฒ ํด๊ฒฐํ๋์ง ์ค์ ํ์ ์๋ ค์ค๊ฒ! ๐ ๏ธ1. ํ์ ์๋ฌ ์ฝ๋ ๋ฒ
ํ์ ์คํฌ๋ฆฝํธ ์๋ฌ ๋ฉ์์ง๋ ์ฒ์์ ๋ณต์กํด ๋ณด์ด์ง๋ง, ํจํด์ ์๋ฉด ์ฌ์:
// ์๋ฌ ์์
Type '{ name: string; age: number; }' is not assignable to type 'User'.
Property 'email' is missing in type '{ name: string; age: number; }'
but required in type 'User'.
์ด ์๋ฌ๋ `User` ํ์
์ ํ์ํ `email` ์์ฑ์ด ์๋ค๋ ๋ป์ด์ผ. ํด๊ฒฐ ๋ฐฉ๋ฒ์:โข `email` ์์ฑ ์ถ๊ฐํ๊ธฐ
โข `User` ํ์ ์์ `email`์ ์ ํ์ ์ผ๋ก ๋ง๋ค๊ธฐ (`email?: string`)
โข `Partial
2. ํ์ ์ขํ๊ธฐ (Type Narrowing)
function processValue(value: string | number) {
// โ ์๋ฌ: Property 'toFixed' does not exist on type 'string | number'
// return value.toFixed(2)
// โ
ํ์
๊ฐ๋๋ก ์ขํ๊ธฐ
if (typeof value === 'number') {
return value.toFixed(2) // ์ด์ value๋ number
}
return value.toUpperCase() // ์ฌ๊ธฐ์ value๋ string
}
// ์ปค์คํ
ํ์
๊ฐ๋
function isUser(obj: any): obj is User {
return obj && typeof obj.id === 'string' && typeof obj.name === 'string'
}
const data: unknown = await fetchData()
if (isUser(data)) {
console.log(data.name) // ํ์
์์ !
}
ํ์
๊ฐ๋๋ ๋ฐํ์ ์ฒดํฌ์ ํ์
์ฒดํฌ๋ฅผ ๋์์ ํด๊ฒฐํด์ค! ๐ฏ3. ์ ๋ค๋ฆญ ํ์ ์๋ฌ ํด๊ฒฐ
// โ ์๋ฌ ๋ฐ์
function getProperty(obj: object, key: string) {
return obj[key] // Element implicitly has an 'any' type
}
// โ
์ ๋ค๋ฆญ์ผ๋ก ํด๊ฒฐ
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key] // ํ์
์์ !
}
const user = { id: '1', name: 'John' }
const name = getProperty(user, 'name') // string ํ์
์ผ๋ก ์ถ๋ก
// const invalid = getProperty(user, 'invalid') // ์ปดํ์ผ ์๋ฌ!
`keyof`์ ์ ๋ค๋ฆญ์ ์กฐํฉํ๋ฉด ๊ฐ์ฒด ์์ฑ ์ ๊ทผ๋ ํ์
์์ ํ๊ฒ ํ ์ ์์ด! ๐โข `Cmd/Ctrl + .`๋ก ๋น ๋ฅธ ์์ ์ ์ ๋ฐ๊ธฐ
โข `F12`๋ก ํ์ ์ ์๋ก ์ด๋
โข `Shift + F12`๋ก ๋ชจ๋ ์ฐธ์กฐ ์ฐพ๊ธฐ
์ด๋ฐ ๊ธฐ๋ฅ๋ค์ ์ ๊ทน ํ์ฉํ๋ฉด ๋๋ฒ๊น ์ด ํจ์ฌ ์ฌ์์ ธ! ๐จ
ํ์ ์ ์๊ฐ ์๋ ๋ผ์ด๋ธ๋ฌ๋ฆฌ๋ฅผ ์ฌ์ฉํ ๋:
// types/my-library.d.ts ํ์ผ ์์ฑ
declare module 'my-library' {
export interface Config {
apiKey: string
timeout?: number
}
export function initialize(config: Config): void
export function getData(): Promise<any>
}
// ์ฌ์ฉ
import { initialize } from 'my-library'
initialize({ apiKey: 'xxx' }) // ํ์
์ฒดํฌ ๋จ!
์ง์ ํ์
์ ์๋ฅผ ์์ฑํ๋ฉด ํ์
์ด ์๋ ๋ผ์ด๋ธ๋ฌ๋ฆฌ๋ ์์ ํ๊ฒ ์ฌ์ฉํ ์ ์์ด! ๐๐ ์ค์ ํ๋ก์ ํธ ๊ตฌ์กฐ์ ๋ฒ ์คํธ ํ๋ํฐ์ค
์ด์ ์ค์ ์์ ์ฌ์ฉํ ์ ์๋ ํ๋ก์ ํธ ๊ตฌ์กฐ์ ๋ฒ ์คํธ ํ๋ํฐ์ค๋ฅผ ์์๋ณด์! ๋๊ท๋ชจ ํ๋ก์ ํธ์์๋ ํ์ ์์ ์ฑ์ ์ ์งํ๋ ๋ฐฉ๋ฒ์ด์ผ. ๐๏ธ์ถ์ฒ ํด๋ ๊ตฌ์กฐ
src/
โโโ pages/ # Next.js ํ์ด์ง
โ โโโ api/ # API ๋ผ์ฐํธ
โ โโโ _app.tsx
โ โโโ index.tsx
โโโ components/ # ์ฌ์ฌ์ฉ ์ปดํฌ๋ํธ
โ โโโ common/
โ โโโ features/
โโโ types/ # ํ์
์ ์
โ โโโ api.ts # API ๊ด๋ จ ํ์
โ โโโ models.ts # ๋ฐ์ดํฐ ๋ชจ๋ธ
โ โโโ index.ts # ํ์
์ฌexport
โโโ lib/ # ์ ํธ๋ฆฌํฐ ํจ์
โ โโโ api.ts
โ โโโ helpers.ts
โโโ hooks/ # ์ปค์คํ
ํ
โโโ contexts/ # Context API
โโโ styles/ # ์คํ์ผ
ํ์
์ ์ ํ์ผ ๊ตฌ์กฐํ// types/models.ts
export interface User {
id: string
name: string
email: string
role: UserRole
createdAt: string
}
export type UserRole = 'admin' | 'user' | 'guest'
export interface Product {
id: string
name: string
price: number
category: Category
}
export interface Category {
id: string
name: string
slug: string
}
// types/api.ts
import type { User, Product } from './models'
export interface ApiResponse<T> {
success: boolean
data?: T
error?: string
message?: string
}
export interface PaginatedResponse<T> {
items: T[]
total: number
page: number
pageSize: number
hasMore: boolean
}
export type GetUsersResponse = ApiResponse<PaginatedResponse<User>>
export type GetProductResponse = ApiResponse<Product>
// types/index.ts (์ค์ ์ง์ค์ export)
export * from './models'
export * from './api'
์ด๋ ๊ฒ ํ์
์ ์ฒด๊ณ์ ์ผ๋ก ๊ด๋ฆฌํ๋ฉด ํ๋ก์ ํธ๊ฐ ์ปค์ ธ๋ ์ ์ง๋ณด์๊ฐ ์ฌ์! ๐ฏAPI ํด๋ผ์ด์ธํธ ํ์ ์์ ํ๊ฒ ๋ง๋ค๊ธฐ
// lib/api.ts
import type { ApiResponse, GetUsersResponse, GetProductResponse } from '@/types'
class ApiClient {
private baseUrl: string
constructor(baseUrl: string) {
this.baseUrl = baseUrl
}
private async request<T>(
endpoint: string,
options?: RequestInit
): Promise<ApiResponse<T>> {
try {
const res = await fetch(`${this.baseUrl}${endpoint}`, {
headers: {
'Content-Type': 'application/json',
...options?.headers
},
...options
})
if (!res.ok) {
return {
success: false,
error: `HTTP ${res.status}`,
message: res.statusText
}
}
const data = await res.json()
return {
success: true,
data
}
} catch (error) {
return {
success: false,
error: 'Network Error',
message: error instanceof Error ? error.message : 'Unknown error'
}
}
}
async getUsers(page: number = 1): Promise<GetUsersResponse> {
return this.request(`/users?page=${page}`)
}
async getProduct(id: string): Promise<GetProductResponse> {
return this.request(`/products/${id}`)
}
async createUser(data: CreateUserInput): Promise<ApiResponse<User>> {
return this.request('/users', {
method: 'POST',
body: JSON.stringify(data)
})
}
}
export const api = new ApiClient(process.env.NEXT_PUBLIC_API_URL!)
// ์ฌ์ฉ
const result = await api.getUsers(1)
if (result.success && result.data) {
console.log(result.data.items) // ํ์
์์ !
}
์ด๋ฐ ์์ผ๋ก API ํด๋ผ์ด์ธํธ๋ฅผ ๋ง๋ค๋ฉด ๋ชจ๋ API ํธ์ถ์ด ํ์
์์ ํด์ ธ! ๐// hooks/useUser.ts
import { useState, useEffect } from 'react'
import type { User, ApiResponse } from '@/types'
import { api } from '@/lib/api'
interface UseUserResult {
user: User | null
loading: boolean
error: string | null
refetch: () => Promise<void>
}
export function useUser(userId: string): UseUserResult {
const [user, setUser] = useState<User | null>(null)
const [loading, setLoading] = useState(true)
const [error, setError] = useState<string | null>(null)
const fetchUser = async () => {
setLoading(true)
setError(null)
const result = await api.getUser(userId)
if (result.success && result.data) {
setUser(result.data)
} else {
setError(result.error || 'Unknown error')
}
setLoading(false)
}
useEffect(() => {
fetchUser()
}, [userId])
return { user, loading, error, refetch: fetchUser }
}
// ์ฌ์ฉ
const { user, loading, error } = useUser('123')
if (user) {
console.log(user.name) // ํ์
์์ !
}
์ปค์คํ
ํ
๋ ๋ฐํ ํ์
์ ๋ช
ํํ ์ ์ํ๋ฉด ์ฌ์ฉํ๊ธฐ ํธํด์ ธ! ๐ฃ
// contexts/AuthContext.tsx
import { createContext, useContext, useState, ReactNode } from 'react'
import type { User } from '@/types'
interface AuthContextValue {
user: User | null
login: (email: string, password: string) => Promise<void>
logout: () => void
isAuthenticated: boolean
}
const AuthContext = createContext<AuthContextValue | undefined>(undefined)
interface AuthProviderProps {
children: ReactNode
}
export function AuthProvider({ children }: AuthProviderProps) {
const [user, setUser] = useState<User | null>(null)
const login = async (email: string, password: string) => {
// ๋ก๊ทธ์ธ ๋ก์ง...
const userData: User = { /* ... */ }
setUser(userData)
}
const logout = () => {
setUser(null)
}
const value: AuthContextValue = {
user,
login,
logout,
isAuthenticated: user !== null
}
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>
}
export function useAuth(): AuthContextValue {
const context = useContext(AuthContext)
if (context === undefined) {
throw new Error('useAuth must be used within AuthProvider')
}
return context
}
// ์ฌ์ฉ
const { user, login, isAuthenticated } = useAuth() // ํ์
์์ !
Context๋ ํ์
์ ์ ๋๋ก ์ ์ํ๋ฉด ์ ์ญ ์ํ ๊ด๋ฆฌ๊ฐ ํจ์ฌ ์์ ํด์ ธ! ๐๐ Next.js 13+ App Router์ ํ์ ์คํฌ๋ฆฝํธ
Next.js 13๋ถํฐ ๋์ ๋ App Router๋ ํ์ ์์คํ ์ด ์กฐ๊ธ ๋ฌ๋ผ. ์ต์ ํจํด์ ์์๋ณด์! ๐์๋ฒ ์ปดํฌ๋ํธ ํ์ ์ ์
// app/users/page.tsx
import type { Metadata } from 'next'
interface User {
id: string
name: string
email: string
}
// ๋ฉํ๋ฐ์ดํฐ export (ํ์
์์ )
export const metadata: Metadata = {
title: '์ฌ์ฉ์ ๋ชฉ๋ก',
description: '๋ชจ๋ ์ฌ์ฉ์๋ฅผ ํ์ธํ์ธ์'
}
// ์๋ฒ ์ปดํฌ๋ํธ๋ async ๊ฐ๋ฅ
export default async function UsersPage() {
const res = await fetch('https://api.example.com/users', {
cache: 'no-store' // SSR
})
const users: User[] = await res.json()
return (
<div>
<h1>์ฌ์ฉ์ ๋ชฉ๋ก</h1>
{users.map(user => (
<div key={user.id}>{user.name}</div>
))}
</div>
)
}
App Router์์๋ ์๋ฒ ์ปดํฌ๋ํธ๊ฐ ๊ธฐ๋ณธ์ด๋ผ `async/await`๋ฅผ ์ง์ ์ฌ์ฉํ ์ ์์ด! ๐๋์ ๋ผ์ฐํธ ํ์ ์ ์
// app/users/[id]/page.tsx
interface PageProps {
params: { id: string }
searchParams: { [key: string]: string | string[] | undefined }
}
export default async function UserDetailPage({ params, searchParams }: PageProps) {
const { id } = params
const { tab = 'profile' } = searchParams
const res = await fetch(`https://api.example.com/users/${id}`)
const user: User = await res.json()
return (
<div>
<h1>{user.name}</h1>
<p>ํ์ฌ ํญ: {tab}</p>
</div>
)
}
// generateStaticParams๋ก ์ ์ ์์ฑ
export async function generateStaticParams() {
const res = await fetch('https://api.example.com/users')
const users: User[] = await res.json()
return users.map(user => ({
id: user.id
}))
}
`params`์ `searchParams`์ ํ์
์ด ๋ช
ํํ๊ฒ ์ ์๋์ด ์์ด! ๐ฏํด๋ผ์ด์ธํธ ์ปดํฌ๋ํธ ํ์
// app/components/Counter.tsx
'use client'
import { useState } from 'react'
interface CounterProps {
initialCount?: number
step?: number
onCountChange?: (count: number) => void
}
export default function Counter({
initialCount = 0,
step = 1,
onCountChange
}: CounterProps) {
const [count, setCount] = useState(initialCount)
const increment = () => {
const newCount = count + step
setCount(newCount)
onCountChange?.(newCount)
}
return (
<div>
<p>Count: {count}</p>
<button onClick={increment}>+{step}</button>
</div>
)
}
ํด๋ผ์ด์ธํธ ์ปดํฌ๋ํธ๋ `'use client'` ์ง์์ด๋ฅผ ์ถ๊ฐํ๊ณ , ์ผ๋ฐ React ์ปดํฌ๋ํธ์ฒ๋ผ ํ์
์ ์ ์ํ๋ฉด ๋ผ! ๐ฑโข ๋ฐ์ดํฐ ํ์นญ์ด ํ์ํ ๊ฒฝ์ฐ
โข ๋ฐฑ์๋ ๋ฆฌ์์ค ์ง์ ์ ๊ทผ
โข ๋ฏผ๊ฐํ ์ ๋ณด ์ฒ๋ฆฌ
โข SEO๊ฐ ์ค์ํ ์ฝํ ์ธ
ํด๋ผ์ด์ธํธ ์ปดํฌ๋ํธ ์ฌ์ฉ:
โข ์ธํฐ๋ํฐ๋ธํ UI
โข ๋ธ๋ผ์ฐ์ API ์ฌ์ฉ (localStorage ๋ฑ)
โข ์ด๋ฒคํธ ๋ฆฌ์ค๋ ํ์
โข useState, useEffect ๋ฑ ํ ์ฌ์ฉ
๊ธฐ๋ณธ์ ์๋ฒ ์ปดํฌ๋ํธ, ํ์ํ ๋๋ง ํด๋ผ์ด์ธํธ ์ปดํฌ๋ํธ! ๐จ
// app/api/users/route.ts
import { NextRequest, NextResponse } from 'next/server'
import type { User } from '@/types'
export async function GET(request: NextRequest) {
const searchParams = request.nextUrl.searchParams
const page = Number(searchParams.get('page')) || 1
try {
const res = await fetch(`https://api.example.com/users?page=${page}`)
const users: User[] = await res.json()
return NextResponse.json({
success: true,
data: users
})
} catch (error) {
return NextResponse.json(
{ success: false, error: 'Failed to fetch users' },
{ status: 500 }
)
}
}
export async function POST(request: NextRequest) {
try {
const body: CreateUserInput = await request.json()
// ์ ํจ์ฑ ๊ฒ์ฌ
if (!body.name || !body.email) {
return NextResponse.json(
{ success: false, error: 'Missing required fields' },
{ status: 400 }
)
}
// ์ฌ์ฉ์ ์์ฑ ๋ก์ง...
const newUser: User = { /* ... */ }
return NextResponse.json(
{ success: true, data: newUser },
{ status: 201 }
)
} catch (error) {
return NextResponse.json(
{ success: false, error: 'Invalid request body' },
{ status: 400 }
)
}
}
App Router์ Route Handler๋ `NextRequest`์ `NextResponse`๋ฅผ ์ฌ์ฉํด์ ํ์
์์ ํ๊ฒ API๋ฅผ ๋ง๋ค ์ ์์ด! ๐๐ฏ ์ค๋ฌด์์ ์์ฃผ ๋ง๋๋ ์๋๋ฆฌ์ค์ ํด๊ฒฐ์ฑ
์ค์ ํ๋ก์ ํธ์์ ์์ฃผ ๋ง์ฃผ์น๋ ์ํฉ๋ค๊ณผ ํด๊ฒฐ ๋ฐฉ๋ฒ์ ๊ณต์ ํ ๊ฒ! ๐ผ์๋๋ฆฌ์ค 1: ์ธ๋ถ API ์๋ต ํ์ ๋ถ์ผ์น
์ธ๋ถ API๊ฐ ๋ฌธ์์ ๋ค๋ฅธ ์๋ต์ ๋ณด๋ผ ๋๊ฐ ์์ด. ์ด๋ด ๋๋:
// ๋ฐํ์ ๊ฒ์ฆ ํจ์ ์์ฑ
function validateUser(data: unknown): data is User {
if (typeof data !== 'object' || data === null) return false
const obj = data as Record<string, unknown>
return (
typeof obj.id === 'string' &&
typeof obj.name === 'string' &&
typeof obj.email === 'string'
)
}
// ์ฌ์ฉ
export const getServerSideProps: GetServerSideProps = async () => {
const res = await fetch('https://api.example.com/user')
const data: unknown = await res.json()
if (!validateUser(data)) {
return { notFound: true }
}
// ์ด์ data๋ User ํ์
return {
props: { user: data }
}
}
๋ฐํ์ ๊ฒ์ฆ๊ณผ ํ์
๊ฐ๋๋ฅผ ์กฐํฉํ๋ฉด ์์ ํด! ๐ก๏ธ์๋๋ฆฌ์ค 2: ํผ ๋ฐ์ดํฐ ํ์ ์์ ํ๊ฒ ์ฒ๋ฆฌ
// Zod ๊ฐ์ ์คํค๋ง ๊ฒ์ฆ ๋ผ์ด๋ธ๋ฌ๋ฆฌ ํ์ฉ
import { z } from 'zod'
const userSchema = z.object({
name: z.string().min(2, '์ด๋ฆ์ 2์ ์ด์์ด์ด์ผ ํฉ๋๋ค'),
email: z.string().email('์ฌ๋ฐ๋ฅธ ์ด๋ฉ์ผ์ ์
๋ ฅํ์ธ์'),
age: z.number().min(18, '18์ธ ์ด์๋ง ๊ฐ์
๊ฐ๋ฅํฉ๋๋ค')
})
type UserFormData = z.infer<typeof userSchema>
export default function SignupForm() {
const handleSubmit = async (formData: FormData) => {
const data = {
name: formData.get('name'),
email: formData.get('email'),
age: Number(formData.get('age'))
}
try {
const validatedData = userSchema.parse(data)
// validatedData๋ UserFormData ํ์
await api.createUser(validatedData)
} catch (error) {
if (error instanceof z.ZodError) {
console.error(error.errors)
}
}
}
return <form action={handleSubmit}>{/* ... */}</form>
}
Zod ๊ฐ์ ๋ผ์ด๋ธ๋ฌ๋ฆฌ๋ฅผ ์ฌ์ฉํ๋ฉด ๋ฐํ์ ๊ฒ์ฆ๊ณผ ํ์
์ถ๋ก ์ ๋์์ ํด๊ฒฐํ ์ ์์ด! ๐์๋๋ฆฌ์ค 3: ๋ณต์กํ ์ํ ๊ด๋ฆฌ
// Reducer ํ์
์ ์
type State = {
users: User[]
loading: boolean
error: string | null
selectedUserId: string | null
}
type Action =
| { type: 'FETCH_START' }
| { type: 'FETCH_SUCCESS'; payload: User[] }
| { type: 'FETCH_ERROR'; payload: string }
| { type: 'SELECT_USER'; payload: string }
| { type: 'CLEAR_SELECTION' }
function userReducer(state: State, action: Action): State {
switch (action.type) {
case 'FETCH_START':
return { ...state, loading: true, error: null }
case 'FETCH_SUCCESS':
return { ...state, loading: false, users: action.payload }
case 'FETCH_ERROR':
return { ...state, loading: false, error: action.payload }
case 'SELECT_USER':
return { ...state, selectedUserId: action.payload }
case 'CLEAR_SELECTION':
return { ...state, selectedUserId: null }
default:
return state
}
}
// ์ฌ์ฉ
const [state, dispatch] = useReducer(userReducer, initialState)
dispatch({ type: 'FETCH_SUCCESS', payload: users }) // ํ์
์์ !
์ ๋์จ ํ์
์ผ๋ก ์ก์
์ ์ ์ํ๋ฉด dispatchํ ๋ ์๋์์ฑ๋ ๋๊ณ ํ์
์ฒดํฌ๋ ์๋ฒฝํด! ๐ฏ// config/index.ts
interface Config {
apiUrl: string
apiKey: string
environment: 'development' | 'staging' | 'production'
features: {
analytics: boolean
debugMode: boolean
}
}
const configs: Record<Config['environment'], Config> = {
development: {
apiUrl: 'http://localhost:3000/api',
apiKey: 'dev-key',
environment: 'development',
features: {
analytics: false,
debugMode: true
}
},
staging: {
apiUrl: 'https://staging-api.example.com',
apiKey: process.env.STAGING_API_KEY!,
environment: 'staging',
features: {
analytics: true,
debugMode: true
}
},
production: {
apiUrl: 'https://api.example.com',
apiKey: process.env.PRODUCTION_API_KEY!,
environment: 'production',
features: {
analytics: true,
debugMode: false
}
}
}
const env = (process.env.NODE_ENV || 'development') as Config['environment']
export const config: Config = configs[env]
// ์ฌ์ฉ
if (config.features.debugMode) {
console.log('Debug mode enabled')
}
ํ๊ฒฝ๋ณ ์ค์ ๋ ํ์
์์ ํ๊ฒ ๊ด๋ฆฌํ๋ฉด ๋ฐฐํฌ ์ค์๋ฅผ ์ค์ผ ์ ์์ด! ๐ฏ๐ ๋ง๋ฌด๋ฆฌํ๋ฉฐ: ํ์ ์์คํ ๊ณผ ํจ๊ป ์ฑ์ฅํ๊ธฐ
์, ์ฌ๊ธฐ๊น์ง ํ์ ์คํฌ๋ฆฝํธ์ Next.js SSR์ ํ์ ์์คํ ์ต์ ํ์ ๋ํด ๊น์ด ์๊ฒ ์์๋ดค์ด! ์ฒ์์ ๋ณต์กํด ๋ณด์ด์ง๋ง, ํ ๋ฒ ์ต์ํด์ง๋ฉด ํ์ ์์คํ ์์ด๋ ๊ฐ๋ฐํ ์ ์์ ๊ฑฐ์ผ. ๐โข Next.js์ ํ์ ์ง์์ ์ ๊ทน ํ์ฉํ์
โข `GetServerSideProps`, `GetStaticProps` ์ ๋ค๋ฆญ ํ์ ์ ์
โข API ๋ผ์ฐํธ๋ ํ์ ์์ ํ๊ฒ
2. ๊ณ ๊ธ ํจํด ํ์ฉ
โข ์ ํธ๋ฆฌํฐ ํ์ ์ผ๋ก ์ฌ์ฌ์ฉ์ฑ ๋์ด๊ธฐ
โข ์ ๋ค๋ฆญ๊ณผ ์กฐ๊ฑด๋ถ ํ์ ์ผ๋ก ์ ์ฐ์ฑ ํ๋ณด
โข ํ์ ๊ฐ๋๋ก ๋ฐํ์ ์์ ์ฑ ๊ฐํ
3. ์ค์ ์ต์ ํ
โข ํ์ ์ํฌํธ ์ต์ ํ๋ก ๋ฒ๋ค ํฌ๊ธฐ ๊ฐ์
โข ์ฆ๋ถ ์ปดํ์ผ๋ก ๋น๋ ์๋ ํฅ์
โข ํ๋ก์ ํธ ๊ตฌ์กฐ ์ฒด๊ณํ
4. ์ง์์ ์ธ ํ์ต
โข ํ์ ์คํฌ๋ฆฝํธ๋ ๊ณ์ ๋ฐ์ ํ๊ณ ์์ด
โข ์ปค๋ฎค๋ํฐ์ ๊ณต์ ๋ฌธ์ ํ์ฉ
โข ์ค์ ํ๋ก์ ํธ์์ ๊ฒฝํ ์๊ธฐ
ํนํ ์๋ฒ์ฌ์ด๋ ๋ ๋๋ง ํ๊ฒฝ์์๋ ํด๋ผ์ด์ธํธ์ ์๋ฒ ์์ชฝ์ ํ์ ์์ ์ฑ์ด ์ ๋ง ์ค์ํด. ๋ฐํ์ ์๋ฌ๋ฅผ ์ปดํ์ผ ํ์์ ์ก์ ์ ์๋ค๋ ๊ฑด ์์ฒญ๋ ์ฅ์ ์ด๊ฑฐ๋ ! ๐ฏ
๊ทธ๋ฆฌ๊ณ ํ์๋ค๊ณผ ํ์ ์ปจ๋ฒค์ ์ ๊ณต์ ํ๋ ๊ฒ๋ ์์ง ๋ง์. ์ผ๊ด๋ ํ์ ์คํ์ผ์ด ์ ์ง๋ณด์๋ฅผ ํจ์ฌ ์ฝ๊ฒ ๋ง๋ค์ด์ค!
ํ์ ์คํฌ๋ฆฝํธ์ Next.js๋ก ์์ ํ๊ณ ํ์ฅ ๊ฐ๋ฅํ ์น ์ ํ๋ฆฌ์ผ์ด์ ์ ๋ง๋ค์ด๋ณด์. ์ฒ์์ ์ด๋ ค์ ๋ณด์ฌ๋, ํ ๊ฑธ์์ฉ ๋์๊ฐ๋ค ๋ณด๋ฉด ์ด๋์ ํ์ ์์คํ ์ ๋ง์คํฐ๊ฐ ๋์ด ์์ ๊ฑฐ์ผ! ๐
ํ๋ณตํ ์ฝ๋ฉ ๋๊ธธ ๋ฐ๋ผ! Happy Typing! ๐โจ
๐ก ์ด ๊ธ์ด ๋์์ด ๋์๋ค๋ฉด, ์ค์ ํ๋ก์ ํธ์ ๋ฐ๋ก ์ ์ฉํด๋ณด์ธ์!
ํ์ ์คํฌ๋ฆฝํธ์ Next.js๋ก ๋ ์์ ํ๊ณ ํ์ฅ ๊ฐ๋ฅํ ์น์ ๋ง๋ค์ด๊ฐ์๋ค! ๐
๊ด๋ จ ํค์๋
๋๊ธ ์์ฑ
์ด ๊ธ์ ๋ํ ์ฌ๋ฌ๋ถ์ ์๊ฐ์ ๋ค๋ ค์ฃผ์ธ์
๋ก๊ทธ์ธ์ด ํ์ํฉ๋๋ค
๋๊ธ์ ์์ฑํ๋ ค๋ฉด ๋จผ์ ๋ก๊ทธ์ธํด์ฃผ์ธ์.
๋๊ธ 0
์ง์์ธ์ ์ฒ - ์ง์ ์ฌ์ฐ๊ถ ๋ณดํธ ๊ณ ์ง
์ง์ ์ฌ์ฐ๊ถ ๋ณดํธ ๊ณ ์ง
- ์ ์๊ถ ๋ฐ ์์ ๊ถ: ๋ณธ ์ปจํ ์ธ ๋ ์ฌ๋ฅ๋ท์ ๋ ์ AI ๊ธฐ์ ๋ก ์์ฑ๋์์ผ๋ฉฐ, ๋ํ๋ฏผ๊ตญ ์ ์๊ถ๋ฒ ๋ฐ ๊ตญ์ ์ ์๊ถ ํ์ฝ์ ์ํด ๋ณดํธ๋ฉ๋๋ค.
- AI ์์ฑ ์ปจํ ์ธ ์ ๋ฒ์ ์ง์: ๋ณธ AI ์์ฑ ์ปจํ ์ธ ๋ ์ฌ๋ฅ๋ท์ ์ง์ ์ฐฝ์๋ฌผ๋ก ์ธ์ ๋๋ฉฐ, ๊ด๋ จ ๋ฒ๊ท์ ๋ฐ๋ผ ์ ์๊ถ ๋ณดํธ๋ฅผ ๋ฐ์ต๋๋ค.
- ์ฌ์ฉ ์ ํ: ์ฌ๋ฅ๋ท์ ๋ช ์์ ์๋ฉด ๋์ ์์ด ๋ณธ ์ปจํ ์ธ ๋ฅผ ๋ณต์ , ์์ , ๋ฐฐํฌ, ๋๋ ์์ ์ ์ผ๋ก ํ์ฉํ๋ ํ์๋ ์๊ฒฉํ ๊ธ์ง๋ฉ๋๋ค.
- ๋ฐ์ดํฐ ์์ง ๊ธ์ง: ๋ณธ ์ปจํ ์ธ ์ ๋ํ ๋ฌด๋จ ์คํฌ๋ํ, ํฌ๋กค๋ง, ๋ฐ ์๋ํ๋ ๋ฐ์ดํฐ ์์ง์ ๋ฒ์ ์ ์ฌ์ ๋์์ด ๋ฉ๋๋ค.
- AI ํ์ต ์ ํ: ์ฌ๋ฅ๋ท์ AI ์์ฑ ์ปจํ ์ธ ๋ฅผ ํ AI ๋ชจ๋ธ ํ์ต์ ๋ฌด๋จ ์ฌ์ฉํ๋ ํ์๋ ๊ธ์ง๋๋ฉฐ, ์ด๋ ์ง์ ์ฌ์ฐ๊ถ ์นจํด๋ก ๊ฐ์ฃผ๋ฉ๋๋ค.
์์ง ๋๊ธ์ด ์์ต๋๋ค.