Getting started
codegen-openapi reads an OpenAPI spec and writes the code your frontend needs to talk to that API:
nextjs | nextjs-pages | react | |
|---|---|---|---|
| Route handlers (server proxy to your backend) | ✅ route.ts | ✅ pages/api/*.ts | — |
| Typed services (one per OpenAPI tag) | ✅ | ✅ | ✅ |
| React hooks | — | — | ✅ |
apiClient.ts (browser Axios instance) | ✅ | ✅ | ✅ |
fetchBackend.ts (server HTTP helper) | ✅ | ✅ | — |
Installation
npm install --save-dev codegen-openapiThe CLI itself has no runtime dependencies. The generated code imports a few libraries, which you install in your app — generate checks your package.json and prints the exact install command for anything missing:
| Package | Needed when |
|---|---|
axios | always (used by apiClient.ts and fetchBackend.ts) |
js-cookie | cookieName is set |
server-only | framework is nextjs or nextjs-pages |
@tanstack/react-query | framework: 'react' with hooksMode: 'react-query' (default) |
# Next.js
npm install axios server-only js-cookie
# React + React Query
npm install axios js-cookie @tanstack/react-queryTIP
The spec must be OpenAPI 3.0 or 3.1, in JSON — or YAML with the yaml package installed in your project. Swagger 2.0 is not supported.
Quick start
Run the interactive wizard in your project root:
npx openapi-gen runIn English or Portuguese, it detects your framework, loads the spec to check it, suggests every value, shows a review of what will be generated, saves openapi-gen.config.mjs, generates everything and offers to install the packages the code needs. Type ? at any question for help.
Add a script so the whole team regenerates the same way:
{
"scripts": {
"codegen": "openapi-gen generate"
}
}Everyday workflow
npx openapi-gen diff # what changed in the spec vs. the files on disk
npx openapi-gen generate # regenerate all files (--prune removes deleted endpoints, --watch keeps running)
npx openapi-gen add # connect another API to the same project
npx openapi-gen info # where files go and which env variables to setGenerated files are overwritten
Every file starts with // Auto-generated by codegen-openapi — do not edit manually. Put your own logic in separate files that import the generated services and hooks.
Using the generated code
Next.js — call the typed service from a client component; it hits your generated route handler, which proxies to the backend:
'use client';
import usersService from '@/services/users';
const users = await usersService.list({ page: 1 });React — use the generated hooks:
import { useList, useCreate } from './hooks/users';
function Users() {
const { data, isLoading } = useList({ page: 1 });
const create = useCreate();
// create.mutate({ body: { name: 'Ana' } })
}Next: see Commands and the Configuration reference.