mock-state-toggle
v0.1.0
Published
Cookie-based mock API state toggle for Next.js development — floating orange button that persists test states via cookies
Maintainers
Readme
mfx-mock-state-toggle
A floating dev-only toggle for Next.js that persists mock API states via cookies. Useful for testing different UI states (empty lists, error states, role-based views) without modifying code.
- Orange floating button (bottom-right) — only visible in non-production
- Cookie-based state persistence — survives page reloads
- Route-aware — shows relevant states for the current page
- Keyboard shortcut — Ctrl+Shift+M clears all states
Quick start
pnpm add mfx-mock-state-toggle// src/app/layout.tsx
import { MockToggleLoader } from 'mfx-mock-state-toggle';
import { ROUTE_CONFIGS } from '@/config/mockRouteConfigs';
export default function RootLayout({ children }) {
return (
<html>
<body>
{children}
<MockToggleLoader routeConfigs={ROUTE_CONFIGS} />
</body>
</html>
);
}// src/config/mockRouteConfigs.ts
import type { RouteConfig } from 'mfx-mock-state-toggle';
export const ROUTE_CONFIGS: RouteConfig[] = [
{
pattern: '/users',
exact: true,
config: {
moduleName: 'Users',
states: [
{ key: 'emptyUserList', label: 'Empty List', description: 'No users', category: 'list' },
{ key: 'errorUserList', label: 'Error', description: 'Load error', category: 'list' },
],
},
},
];// src/app/api/users/route.ts
import { cookies } from 'next/headers';
import { hasMockState, MOCK_API_STATES_COOKIE } from 'mfx-mock-state-toggle';
export async function GET() {
const mock = (await cookies()).get(MOCK_API_STATES_COOKIE)?.value;
if (hasMockState(mock, 'emptyUserList')) return Response.json({ users: [] });
if (hasMockState(mock, 'errorUserList')) return Response.json({ error: '...' }, { status: 500 });
return Response.json({ users: await db.getUsers() });
}Hidden automatically when NEXT_PUBLIC_MODE=production.
Docs
| File | Contents | |---|---| | INTEGRATION.md | Full setup guide — all required files and config | | LOCAL-DEV.md | Symlinking for local development across projects | | PUBLISHING.md | How to publish to npm |
Exports
| Export | Type | Use |
|---|---|---|
| MockToggleLoader | Component | Mount in root layout |
| MockStateToggle | Component | Use directly with a config (no route detection) |
| useMockStateToggle | Hook | Build a custom toggle UI |
| getConfigForRoute | Function | Match a pathname against route configs |
| hasMockState | Function | Check active states server-side |
| MOCK_API_STATES_COOKIE | Constant | Cookie name for reading/writing states |
| API_SIMULATION_TIMEOUT | Constant | Default timeout (500ms) for mock delays |
| isProductionEnvironment | Function | Returns true when NEXT_PUBLIC_MODE=production |
| MockStateConfig | Type | Config shape for a module |
| MockStateOption | Type | Individual mock state definition |
| RouteConfig | Type | Route-to-config mapping |
Requirements
- Next.js ≥ 14
- React ≥ 18
- Tailwind CSS (v3 or v4)
