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:

export default (req, res) => {
  res.statusCode = 200
  res.setHeader('Content-Type', 'application/json')
  res.end(JSON.stringify({ message: 'hello' }))
}
curl -X PUT http://localhost:3000/api/example
 
{"message":"hello"}

The package next-connect helps to split our logic based on the methods (GET, PUT, DELETE, etc.) :

yarn add next-connect
import nc from "next-connect";

const handler = nc()
  // express like routing for methods
  .get((req, res) => {
    res.send({ message: "ok" });
  })
  .post((req, res) => {
    res.json({ message: "posted" });
  });

export default handler;

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.

export default function handler(req, res) {  
const email = req.body.email 
// Then save email to your database, etc
}

Preview Mode

Static 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 Routes

API Routes can be dynamic, just like regular pages. Take a look at our Dynamic API Routes documentation to learn more.

Last updated