1. 아래의 명령어를 입력하여, SQLite 패키지를 설치한다.
npm install better-sqlite3
2. Root 경로에 파일을 생성하고 아래의 코드를 입력한다. 파일 이름은 "initdb.js"이라고 지었다.
const sql = require('better-sqlite3');
const db = sql('meals.db');
const dummyMeals = [
{
title: 'Juicy Cheese Burger',
slug: 'juicy-cheese-burger',
image: '/images/burger.jpg',
summary:
'A mouth-watering burger with a juicy beef patty and melted cheese, served in a soft bun.',
instructions: `
1. Prepare the patty:
Mix 200g of ground beef with salt and pepper. Form into a patty.
2. Cook the patty:
Heat a pan with a bit of oil. Cook the patty for 2-3 minutes each side, until browned.
3. Assemble the burger:
Toast the burger bun halves. Place lettuce and tomato on the bottom half. Add the cooked patty and top with a slice of cheese.
4. Serve:
Complete the assembly with the top bun and serve hot.
`,
creator: 'John Doe',
creator_email: 'johndoe@example.com',
},
{
title: 'Spicy Curry',
slug: 'spicy-curry',
image: '/images/curry.jpg',
summary:
'A rich and spicy curry, infused with exotic spices and creamy coconut milk.',
instructions: `
1. Chop vegetables:
Cut your choice of vegetables into bite-sized pieces.
2. Sauté vegetables:
In a pan with oil, sauté the vegetables until they start to soften.
3. Add curry paste:
Stir in 2 tablespoons of curry paste and cook for another minute.
4. Simmer with coconut milk:
Pour in 500ml of coconut milk and bring to a simmer. Let it cook for about 15 minutes.
5. Serve:
Enjoy this creamy curry with rice or bread.
`,
creator: 'Max Schwarz',
creator_email: 'max@example.com',
},
{
title: 'Homemade Dumplings',
slug: 'homemade-dumplings',
image: '/images/dumplings.jpg',
summary:
'Tender dumplings filled with savory meat and vegetables, steamed to perfection.',
instructions: `
1. Prepare the filling:
Mix minced meat, shredded vegetables, and spices.
2. Fill the dumplings:
Place a spoonful of filling in the center of each dumpling wrapper. Wet the edges and fold to seal.
3. Steam the dumplings:
Arrange dumplings in a steamer. Steam for about 10 minutes.
4. Serve:
Enjoy these dumplings hot, with a dipping sauce of your choice.
`,
creator: 'Emily Chen',
creator_email: 'emilychen@example.com',
},
{
title: 'Classic Mac n Cheese',
slug: 'classic-mac-n-cheese',
image: '/images/macncheese.jpg',
summary:
"Creamy and cheesy macaroni, a comforting classic that's always a crowd-pleaser.",
instructions: `
1. Cook the macaroni:
Boil macaroni according to package instructions until al dente.
2. Prepare cheese sauce:
In a saucepan, melt butter, add flour, and gradually whisk in milk until thickened. Stir in grated cheese until melted.
3. Combine:
Mix the cheese sauce with the drained macaroni.
4. Bake:
Transfer to a baking dish, top with breadcrumbs, and bake until golden.
5. Serve:
Serve hot, garnished with parsley if desired.
`,
creator: 'Laura Smith',
creator_email: 'laurasmith@example.com',
},
{
title: 'Authentic Pizza',
slug: 'authentic-pizza',
image: '/images/pizza.jpg',
summary:
'Hand-tossed pizza with a tangy tomato sauce, fresh toppings, and melted cheese.',
instructions: `
1. Prepare the dough:
Knead pizza dough and let it rise until doubled in size.
2. Shape and add toppings:
Roll out the dough, spread tomato sauce, and add your favorite toppings and cheese.
3. Bake the pizza:
Bake in a preheated oven at 220°C for about 15-20 minutes.
4. Serve:
Slice hot and enjoy with a sprinkle of basil leaves.
`,
creator: 'Mario Rossi',
creator_email: 'mariorossi@example.com',
},
{
title: 'Wiener Schnitzel',
slug: 'wiener-schnitzel',
image: '/images/schnitzel.jpg',
summary:
'Crispy, golden-brown breaded veal cutlet, a classic Austrian dish.',
instructions: `
1. Prepare the veal:
Pound veal cutlets to an even thickness.
2. Bread the veal:
Coat each cutlet in flour, dip in beaten eggs, and then in breadcrumbs.
3. Fry the schnitzel:
Heat oil in a pan and fry each schnitzel until golden brown on both sides.
4. Serve:
Serve hot with a slice of lemon and a side of potato salad or greens.
`,
creator: 'Franz Huber',
creator_email: 'franzhuber@example.com',
},
{
title: 'Fresh Tomato Salad',
slug: 'fresh-tomato-salad',
image: '/images/tomato-salad.jpg',
summary:
'A light and refreshing salad with ripe tomatoes, fresh basil, and a tangy vinaigrette.',
instructions: `
1. Prepare the tomatoes:
Slice fresh tomatoes and arrange them on a plate.
2. Add herbs and seasoning:
Sprinkle chopped basil, salt, and pepper over the tomatoes.
3. Dress the salad:
Drizzle with olive oil and balsamic vinegar.
4. Serve:
Enjoy this simple, flavorful salad as a side dish or light meal.
`,
creator: 'Sophia Green',
creator_email: 'sophiagreen@example.com',
},
];
db.prepare(`
CREATE TABLE IF NOT EXISTS meals (
id INTEGER PRIMARY KEY AUTOINCREMENT,
slug TEXT NOT NULL UNIQUE,
title TEXT NOT NULL,
image TEXT NOT NULL,
summary TEXT NOT NULL,
instructions TEXT NOT NULL,
creator TEXT NOT NULL,
creator_email TEXT NOT NULL
)
`).run();
async function initData() {
const stmt = db.prepare(`
INSERT INTO meals VALUES (
null,
@slug,
@title,
@image,
@summary,
@instructions,
@creator,
@creator_email
)
`);
for (const meal of dummyMeals) {
stmt.run(meal);
}
}
initData();
3. 아래의 명령어를 입력하여, 위에서 만든 'initdb.js' 파일의 DB 파일을 생성한다.
node initdb.js
해당 명령어의 결과로 meals.db 파일이 root에 만들어진다.
4. Root에 lib 폴더를 만들고 meals.js라는 파일을 만들고 아래와 같이 입력한다.
import sql from 'better-sqlite3';
const db = sql('meals.db');
export function getMeals() {
return db.prepare('SELECT * FROM meals').all();
}
'getMeals'를 async를 통한 Promise를 사용하지 않았다. NextJS의 Server Component는 async function을 사용할 수 있기 때문이다. 아래는 Server Component를 사용한 코드의 예시이다.
import Link from 'next/link';
import classes from './page.module.css';
import MealsGrid from '@/components/meals/meals-grid';
import { getMeals } from '@/lib/meals';
export default async function MealsPage() {
const meals = await getMeals();
return (
<>
<header className={classes.header}>
<h1>
Delicious meals, created{` `}
<span className={classes.highlight}>by you</span>
</h1>
<p>
Choose your favorite recipe and cook it yourself. It is easy and fun{' '}
</p>
<p className={classes.cta}>
<Link href='/meals/share'>Share Your Favorite Recipe</Link>
</p>
</header>
<main className={classes.main}>
<MealsGrid meals={meals} />
</main>
</>
);
}
일반적인 바닐라 React는 'useEffect' 훅을 사용하여 API에 접근하여 데이터를 가져온다. 하지만, NextJS는 이미 백엔드를 가지고 있기에 useEffect 등과 같은 훅을 사용하지 않아도 DB에 접근할 수 있다. NextJS의 모든 Component는 기본적으로 Server Component이기 때문이다.
'NextJS' 카테고리의 다른 글
| [NextJS] 클라이언트 측에서 백엔드 API 데이터 가져오기 (feat. useEffect) (0) | 2025.10.18 |
|---|---|
| [NextJS] Pre-Renders(사전 랜더링) Page(페이지) (0) | 2024.04.20 |
| [NextJS] Server와 Client 컴포넌트 각각 언제 사용해야할까? (0) | 2024.03.15 |
| [NextJS] 이미지 컴포넌트 사용하기 (0) | 2024.03.13 |
| [NextJS] 페이지 컴포넌트 props (0) | 2024.03.04 |