API Routes let you create an API endpoint inside a Next.js app. You can do so by creating a function inside the pages/api directory that has the following format:
// req = request data, res = response data export default (req, res) => { // ... }
They can be deployed as Serverless Functions (also known as Lambdas).
Let’s try it out. Create a file called hello.js in pages/api with the following code:
export default (req, res) => { res.status(200).json({ text: 'Hello' }) }
Try accessing it at http://localhost:3000/api/hello. You should see {"text":"Hello"}. Note that:
req is an instance of http.IncomingMessage, plus some pre-built middlewares you can see here.res is an instance of http.ServerResponse, plus some helper functions you can see here.That’s it! Before we wrap up this lesson, let’s talk about some tips for using API Routes on the next page.