About EndpointX

EndpointX is an open-source project available on GitHub.

You can view the source code, report issues, suggest ideas,
or contribute to the project

https://github.com/robnsiov/endpointx

If you find a bug, have an improvement idea, want to help
improve the documentation, or have any feedback, feel free to contact me.

Email: robnsiov@gmail.com

Thank you for supporting open-source development ❤️ .

Ctrl+K

Examples and Recipes

This page provides a collection of practical, real-world examples to help you build functional mock APIs quickly. You can copy these snippets directly into your EndpointX routes and modify them to fit your specific frontend, mobile, or testing requirements.

Every example demonstrates how to effectively utilize the secure sandbox, including global objects like db and process.env, as well as built-in utilities like axios() and signJWT().

Data Pagination and Filtering

When building UI components like data tables or infinite scroll lists, your mock API needs to support pagination and search parameters. This example demonstrates how to read searchParams and return a specific slice of the JSON Database.

CRUD Operations

Reading Data

export async function GET() {
  const users = db.users;
 
  console.log(users);
 
  return {
    status: 200,
    body: users,
  };
}

Find by ID (Route Parameters)

export async function GET() {
  const user = db.users.find((user) => user.id === params.id);
 
  console.log(params);
  console.log(user);
 
  if (!user) {
    return {
      status: 404,
      body: {
        message: 'User not found',
      },
    };
  }
 
  return {
    status: 200,
    body: user,
  };
}

Filter with Search Parameters

http://127.0.0.1:3000/api/v1/users?role=admin
export async function GET() {
  const users = db.users.filter((user) => {
    return user.role === searchParams.role;
  });
 
  console.log(searchParams);
  console.log(users);
 
  return {
    status: 200,
    body: users,
  };
}

Create

export async function POST() {
  const user = {
    id: UUID(),
    name: 'John Doe',
    email: 'john@example.com',
    role: 'user',
    createdAt: new Date().toISOString(),
  };
 
  if (!db.users) db.users = [];
 
  db.users.push(user);
 
  console.log(user);
 
  return {
    status: 201,
    db,
    body: user,
  };
}

Update

export async function PATCH() {
  const user = db.users.find((user) => user.id === params.id);
 
  if (!user) {
    return {
      status: 404,
      body: {
        message: 'User not found',
      },
    };
  }
 
  user.name = 'Jane Doe';
  user.updatedAt = new Date().toISOString();
 
  console.log(user);
 
  return {
    status: 200,
    db,
    body: user,
  };
}

Delete

export async function DELETE() {
  const index = db.users.findIndex((user) => user.id === params.id);
 
  if (index === -1) {
    return {
      status: 404,
      body: {
        message: 'User not found',
      },
    };
  }
 
  const deletedUser = db.users.splice(index, 1)[0];
 
  console.log(deletedUser);
 
  return {
    status: 200,
    db,
    body: {
      message: 'User deleted successfully',
    },
  };
}

Custom Response Headers

You can customize the response by returning a headers object.

For security reasons, only headers beginning with x-app- are allowed.

export async function GET() {
  return {
    status: 200,
    headers: {
      'x-app-version': '1.0.0',
      'x-app-request-id': UUID(),
      'x-app-cache': 'MISS',
    },
    body: {
      message: 'Success',
    },
  };
}

JWT Authentication Flow

Mocking an authentication system is a common requirement for frontend development. EndpointX provides signJWT() and jwtVerify() utilities to seamlessly create login endpoints and protected routes.

export async function POST() {
  const { email, password } = body || {};
  const secret = process.env.JWT_SECRET;
 
  if (!secret) return { status: 500, body: { error: 'Missing JWT_SECRET' } };
 
  // Mock validation
  if (email !== 'admin@example.com' || password !== 'password123') {
    return { status: 401, body: { error: 'Invalid credentials' } };
  }
 
  try {
    // Create token with a subject and role
    const token = await signJWT(
      {
        sub: UUID(),
        email: email,
        role: 'admin',
      },
      secret,
    );
 
    return {
      status: 200,
      body: { token: token, message: 'Login successful' },
    };
  } catch (err) {
    return { status: 500, body: { error: 'Token generation failed' } };
  }
}
export async function GET() {
  const authHeader = headers['x-app-authorization'];
  const secret = process.env.JWT_SECRET;
 
  if (!authHeader || !authHeader.startsWith('Bearer ')) {
    return {
      status: 401,
      body: { error: 'Missing or malformed Authorization header' },
    };
  }
 
  const token = authHeader.split(' ')[1];
 
  try {
    // jwtVerify throws an error if the token is invalid or tampered with
    const decoded = await jwtVerify(token, secret);
 
    return {
      status: 200,
      body: {
        message: 'Access granted',
        userProfile: decoded,
        sensitiveData: 'This is a protected resource.',
      },
    };
  } catch (err) {
    console.log('Token verification failed:', err.message);
    return { status: 403, body: { error: 'Invalid or expired token' } };
  }
}