In this tutorial, we'll guide you through building a simple full-stack application using Next.js 14. Our app will include a frontend UI, API routes for backend logic, and a database to store data.
Prerequisites
Before we begin, ensure you have the following installed:
- Node.js (LTS version recommended)
- npm or yarn
- A code editor (VS Code recommended)
- Basic knowledge of React and JavaScript
Step 1: Set Up a Next.js 14 Project
Run the following command to create a new Next.js app:
npx create-next-app@latest my-fullstack-app
cd my-fullstack-app
You can also use yarn
or pnpm
instead of npx
if preferred.
Start the development server:
npm run dev
Visit http://localhost:3000
to see your new Next.js app in action.
Step 2: Create a Simple API Route
Next.js provides API routes for building a backend within your app. Create a new API route:
Create a file at pages/api/hello.js
:
export default function handler(req, res) {
res.status(200).json({ message: "Hello from Next.js API!" });
}
Now visit http://localhost:3000/api/hello
to see the API response.
Step 3: Set Up a Database (Prisma + SQLite)
We'll use Prisma with SQLite for simplicity. Install Prisma:
npm install @prisma/client @prisma/cli
Initialize Prisma:
npx prisma init
Edit prisma/schema.prisma
to use SQLite:
datasource db {
provider = "sqlite"
url = "file:./dev.db"
}
model Task {
id Int @id @default(autoincrement())
title String
done Boolean @default(false)
}
Run the following command to apply changes:
npx prisma migrate dev --name init
Step 4: Create an API Route for Tasks
Create a new API route at pages/api/tasks.js
:
import { PrismaClient } from "@prisma/client";
const prisma = new PrismaClient();
export default async function handler(req, res) {
if (req.method === "GET") {
const tasks = await prisma.task.findMany();
res.status(200).json(tasks);
} else if (req.method === "POST") {
const { title } = req.body;
const newTask = await prisma.task.create({ data: { title } });
res.status(201).json(newTask);
}
}
Step 5: Create a Frontend to Display Tasks
Modify pages/index.js
:
import { useState, useEffect } from "react";
export default function Home() {
const [tasks, setTasks] = useState([]);
useEffect(() => {
fetch("/api/tasks")
.then(res => res.json())
.then(data => setTasks(data));
}, []);
return (
<div>
<h1>Task List</h1>
<ul>
{tasks.map(task => (
<li key={task.id}>{task.title}</li>
))}
</ul>
</div>
);
}
Run your app and visit http://localhost:3000
to see your tasks!
Conclusion
Congratulations! You've built a simple full-stack app using Next.js 14, Prisma, and SQLite. You can extend this by adding user authentication, advanced CRUD operations, and a better UI.
If you're interested in learning more, check out the Next.js documentation and Prisma documentation.
Happy coding!