DEV Community

Cover image for Let's learn about Next.js API routes shortly
Tonmoy Roy
Tonmoy Roy

Posted on

Let's learn about Next.js API routes shortly

Need a backend / API for your project? No problem.

Next.js is a wonderful production-ready framework built on the JavaScript library React. It's extremely flexible letting us build simple static sites, server-side rendered apps, or a mix of both. One of the cool features of Next.js is how it handles the routing system.
Routes can simply be created by adding a file into the /pages folder that is created for you when you bootstrap an app with create-next-app. Inside of here there is another folder called api. When you create a file inside of an api it will be accessible at the route /api/.... But you won't be served with a page this time.
This is an API endpoint belonging to the server-side of your app and is intended to return data, not pages. Here we can write backend code using Node.js if we desire.

*Why should we use the /api routes

A nice way of thinking about a Next.js API route is as a middle-man for your app. Time for an analogy! πŸ˜ƒ
Consider a person called John who wants to send a letter to his friend Jane. Once Jane receives the letter she will send a reply back to John. But how do the letters get from one place to another? The Postman/Postwoman of course!
The Postman/Postwoman acts as the middleman. This person handles the logic of transporting the letters where they need to be and this is kind of what we do with Next.js API routes. Often we make a request to an API route with some data. This is like posting your mail into the letterbox.
Then behind the scenes, the post will go through things like sorting and manipulation before being sent to the other end (like an external API). When the person receives and replies to the letter, eventually the original sender will open the reply (response).

Top comments (0)

11 Tips That Make You a Better Typescript Programmer


1 Think in {Set}

Type is an everyday concept to programmers, but it’s surprisingly difficult to define it succinctly. I find it helpful to use Set as a conceptual model instead.

#2 Understand declared type and narrowed type

One extremely powerful typescript feature is automatic type narrowing based on control flow. This means a variable has two types associated with it at any specific point of code location: a declaration type and a narrowed type.

#3 Use discriminated union instead of optional fields


Read the whole post now!