Javascript is required
3 min read

Use Nitro as Mock Server

Use Nitro as Mock Server Image

Nitro is a server toolkit that allows you to create web servers with everything you need and deploy them wherever you prefer. It's used in Nuxt 3 to power the server-side part of your Nuxt applications.

In this article, I will show how you can use Nitro as a mock server for your frontend E2E tests.

Setup Nitro

First, you need to create a new Nitro project, you can use the official starter template:

npx giget@latest nitro mock-server --install

Then, you can start the Nitro server in the newly created mock-server directory:

npm run dev

Your Nitro server is now running on http://localhost:3000.

Mock API

To mock API endpoints, you can use the full power of Nitro's server routes. Defining a route is as simple as creating a file inside the api/ or routes/ directory.

Here is an example of how you can create a simple mock API endpoint with a dynamic route parameter:

1// /routes/users/[id].get.ts
2export default defineEventHandler(async (event) => {
3  const id = getRouterParam(event, 'id')
5  // Do something with id
7  return `User profile!`

Nitro's server routes are very powerful and flexible, you can use them to create any kind of API endpoint you need.

Integrate in E2E setup

Now that you have a mock server running, you can use it in your frontend E2E tests. Let's do it exemplary with Playwright.


This repository contains the demo code which I describe below.

Let me first introduce the basic setup of the Nuxt 3 demo application that I use for this article:

The application uses one server API endpoint that fetches users from an API endpoint that is configured in the .env file:


In this example, we would like to mock this API endpoint to avoid making real API requests during our E2E tests. Therefore, we want to replace it with our Nitro mock server:


To use the Nitro server in your Playwright tests, you can start the Nitro server in the background before running the tests using the start-server-and-test npm package:

2  "scripts": {
3    "start-mock-server": "npm run --prefix mock-server start",
4    "dev:e2e": "dotenv -e ./.env.e2e -- playwright test --ui",
5    "test:e2e:ui": "start-server-and-test start-mock-server 5005 dev:e2e"
6  },

The Playwright configuration file starts the web server of your frontend application before running the tests:

1import { defineConfig, devices } from '@playwright/test'
3export default defineConfig({
4  // ....
6  /* Run your local dev server before starting the tests */
7  webServer: {
8    command: 'pnpm run dev',
9    reuseExistingServer: !process.env.CI,
10    url: 'http://localhost:3000',
11  },

That's it! Now you can run your E2E tests with the Nitro mock server running in the background: