How to Setup JSON Server with react
After setup the Json server with react we can interact with REST APIs using fetch()
or axios
, which is crucial for real-world React development.
🚀 Goal
- Setup JSON Server
- Store and retrieve users from a
db.json
file - Replace
localStorage
with real API calls for signup/login
📦 1. Install JSON Server (Globally or Locally)
Option A – Install globally (recommended)
npm install -g json-server
Option B – Install locally in your project
npm install json-server --save-dev
📁 2. Create db.json
File in Your Project Root
{
"users": [
{
"id": 1,
"name": "Dharmender Singh",
"email": "dharmender@example.com",
"password": "123456"
},
{
"id": 2,
"name": "Amit",
"email": "amit@example.com",
"password": "password"
}
],
"products": [
{
"id": 1,
"name": "Laptop",
"price": 599,
"description": "High performance laptop for work and gaming."
},
{
"id": 2,
"name": "Smartphone",
"price": 299,
"description": "Latest model with amazing camera."
}
]
}
▶️ 3. Run the JSON Server
In your terminal, run:
json-server --watch db.json --port 5000
✅ It starts a REST API at:
http://localhost:5000/users
🧪 Test API in Browser
Try opening:
http://localhost:5000/users
How to run Json Server:
✅ Option 1: Run JSON Server in a separate terminal
This is the simplest and most common method:
▶️ Steps:
- Terminal 1: Run your React app
npm run dev
Terminal 2: Run JSON Server
json-server --watch db.json --port 5000
💡 JSON Server can run from anywhere, as long as the db.json
file path is correct. But it’s best to place db.json
in your project root and run it from there.
✅ Option 2: Run both in one terminal using concurrently
If you want both servers to run in one command, use the concurrently
package.
📦 Step-by-step
- Install
concurrently
as a dev dependency:
npm install concurrently --save-dev
2. Add this to your package.json
→ scripts
section:
"scripts": {
"dev": "concurrently \"npm run react\" \"npm run server\"",
"react": "vite",
"server": "json-server --watch db.json --port 5000"
}
3 Run both together:
npm run dev
✅ This will start:
- React app on
http://localhost:5173
- JSON Server on
http://localhost:5000
Keep Learning 🙂