Mocking API Responses using the public directory in NextJS

Abenezer Belachew

Abenezer Belachew Β· January 09, 2025

2 min read

When developing a Next.js application, you might need to mock API requests to test your components or pages. There are a lot of ways to do this, but the simplest way is to use the public directory. Files in the public directory are directly accessible from the root URL of your application, which makes it easy to mock API responses. This allows for quickly replicating static API responses without setting up a dedicated mock server.

Let's say you want to return a list of users from an API. You can create a JSON file in the public directory and fetch it using fetch or any other method.

public/mockApi.json
{
  "users": [
    { "id": 1, "name": "Alice" },
    { "id": 2, "name": "Bob" },
    { "id": 3, "name": "Charlie" },
    { "id": 4, "name": "David" }
  ]
}

and then you simply drop this json file in the public directory:

public
└── mockApi.json
  • Now nextjs serves this file at the root URL of your application. (e.g., http://localhost:3000/mockApi.json).

In your component or page, you can fetch this JSON file like this:

const fetchUsers = async () => {
  const response = await fetch('/mockApi.json'); // Fetch from public folder
  if (!response.ok) {
    throw new Error('Failed to fetch users');
  }
  return response.json();
};

This is for the very basic use cases, but you're better off using route handlers for more complex scenarios.

🀺️