Now that the BFF (Backend-for-Frontend) server provides a real API, it’s time to stop using Mock APIs and start integrating with the actual backend.
By leveraging Swagger (OpenAPI) documentation, we can achieve type safety and automated API calls.
swagger-typescript-api is a library that generates TypeScript API code automatically from an OpenAPI (Swagger) document, with full type inference support.
Reference: swagger-typescript-api GitHub
// package.json
"scripts": {
...,
"api": "swagger-typescript-api -p {OpenAPI_DOC_URL} -o ./src -n api.ts"
}
-p: Path or URL to the OpenAPI document-o: Output directory for the generated file-n: Name of the generated file (e.g., api.ts)// package.json
"scripts": {
...,
"api": "swagger-typescript-api -p {OpenAPI_DOC_URL} -o ./src -n api.ts --axios"
}
import {Api} from './api'
const api = new Api({
baseURL: 'http://localhost:3000'
})
baseURL, headers, interceptors, etc.When the client and API server are on different domains, CORS errors may occur.
A Reverse Proxy can route client requests through the local domain to bypass CORS restrictions.
// vite.config.ts
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
export default defineConfig({
plugins: [react()],
server: {
proxy: {
'/api': {
target: 'https://api.example.com', // Real API domain
changeOrigin: true,
rewrite: (path) => path.replace(/^\/api/, ''),
},
},
},
});
/api/...https://api.example.com/...