1 min read

How to use json-server as a backend for your practice apps

Building a custom backend for your apps can be fun and is definitely something I recommend doing at some point. But when you're in the middle of learning React and you just want to practice frontend concepts, it's great if you don't have to code a backend from scratch.

This is where json-server comes in - it's a simple backend server that allows you to have a full REST API based on just a JSON file you define locally. You can add, edit, remove items from the json collection, and the file gets updated, acting like a local database.

Here's an example "database" for a notes app:

// db.json
    "notes": [
            "id": 1,
            "title": "jane's phone number",
            "content": "555 666 777"
            "id": 2,
            "title": "shopping list",
            "content": "- milk\n-strawberries"

When you start the json-sever with by calling json-server db.json, it will start a server at http://localhost:3000 with a REST endpoint dedicated to the notes, for doing CRUD operations on them:

GET    /notes 
GET    /notes/:id
POST   /notes 
PUT    /notes/:id
PATCH  /notes/:id
DELETE /notes/:id

This is usually all you need to get started with your frontend app!

For development, I usually recommend adding the command to start the server to your package.json, so you can run it with a simple npm run backend-server:

// package.json
"scripts": {
    "dev": "vite",
    "test": "vitest",
    "backend-server": "json-server db.json"

And what if you want to simulate a server error?
The simplest way is to just stop the server with Ctrl+C - then the frontend will get a 500 Server Unavailable error.
Another way is to use Chrome's Network tab > throtling to simulate being offline.

Alternatively, if you're looking to throw validation errors, you could set up an express sever that uses json-server as a module, but it's probably not worth the trouble for most practice apps.

I hope you find this useful!