17. Next.js Tutorial (4). API Routes

 1. Create an API Route

Source: https://nextjs.org/learn/basics/api-routes/creating-api-routes

The files must be in the pages/api folder. In this example (pages/api/hello.ts), that can be accessed by http://localhost:3000/api/hello and will return {"text":"Hello"}

export default function handler(req, res) {
  res.status(200).json({ text: 'Hello' });
}

Note: Don't fetch an api route from getStaticprops or getStaticPaths

You can save to a DB some info from a form:

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




Comentarios

Entradas populares de este blog

14. Next.js Tutorial (1)

15. Next.js Tutorial (2). Fetching data. Async functions getStaticProps, getServerSideProps, getStaticPaths

16. Next.js Tutorial (3). Dynamic Routes. Async functions getStaticPaths and getStaticProps