I have a project that I wrote in next js and used json-server for the fake backend. The problem is that I can't deploy the project to vercel because json-server doesn't start when building the project
I tried running multiple scripts at once using concurrently in verel, but that didn't work. Here is the command:
"scripts": {
"build": "next build",
"start": "next start",
"json-server": "json-server --watch db.json --port 5000",
"deploy": "concurrently \"npm run json-server\" \"npm run build && npm run start\"",
},
You can create another endpoint to return fake backend because of NextJS can use as a backend service.
Your API with NextJS
// pages/api/posts.js
export default function handler(req, res) {
const posts = [
{ id: 1, title: "Post 1", content: "This is post 1" },
{ id: 2, title: "Post 2", content: "This is post 2" },
];
res.status(200).json(posts);
}
Your component:
import { useEffect, useState } from 'react';
export default function Home() {
const [posts, setPosts] = useState([]);
useEffect(() => {
fetch('/api/posts')
.then((response) => response.json())
.then((data) => setPosts(data));
}, []);
return (
<div>
<h1>Posts</h1>
<ul>
{posts.map((post) => (
<li key={post.id}>
<h2>{post.title}</h2>
<p>{post.content}</p>
</li>
))}
</ul>
</div>
);
}