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.jsonfile - Replace
localStoragewith 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
concurrentlyas 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 π
