NextJs — Full Stack Next.js Example
Combine all concepts to create a full-stack app: static pages, server-side rendering, API routes, authentication, and deployment.
pages/api/todos.js
let todos = [];
export default function handler(req, res) {
if (req.method === 'GET') return res.status(200).json(todos);
if (req.method === 'POST') {
const todo = { id: Date.now(), text: req.body.text };
todos.push(todo);
return res.status(201).json(todo);
}
res.status(405).end();
}
pages/index.js
import { useState } from 'react';
export default function Home() {
const [todo, setTodo] = useState('');
const addTodo = async () => {
await fetch('/api/todos', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ text: todo }),
});
};
return (
<div>
<input value={todo} onChange={(e) => setTodo(e.target.value)} />
<button onClick={addTodo}>Add Todo</button>
</div>
);
}