API in Next JS
Next.js is a full-stack framework. You can legit ship an API right next to your App with no setup.
Any file inside the folder pages/api
is mapped to /api/*
and will be treated as an API endpoint instead of a page
. They are server-side only bundles and won't increase your client-side bundle size.
/pages/api/example.js:
The package next-connect
helps to split our logic based on the methods (GET, PUT, DELETE, etc.) :
A good use case for API Routes is handling form input. For example, you can create a form on your page and have it send a
POST
request to your API Route. You can then write code to directly save it to your database. The API Route code will not be part of your client bundle, so you can safely write server-side code.
Preview ModeStatic Generation is useful when your pages fetch data from a headless CMS. However, it’s not ideal when you’re writing a draft on your headless CMS and want to preview the draft immediately on your page. You’d want Next.js to render these pages at request time instead of build time and fetch the draft content instead of the published content. You’d want Next.js to bypass Static Generation only for this specific case.
Next.js has a feature called Preview Mode to solve the problem above, and it utilizes API Routes. To learn more about it take a look at our Preview Mode documentation.
Dynamic API RoutesAPI Routes can be dynamic, just like regular pages. Take a look at our Dynamic API Routes documentation to learn more.
Last updated