DEV Community

Basem Salah
Basem Salah

Posted on

what is the benefits of api routes in next js

when i fetch data what is the difference between 2 way of fetching .. the traditional way in page or component by making a call with external api endpoint (Backend) http://example/... and anther way by using api route api/example

Top comments (8)

Collapse
 
joelbonetr profile image
JoelBonetR ๐Ÿฅ‡ • Edited

Either I didn't understand the post or there's a bit of misconception in it.

/api/ directory is meant for you to code endpoints in it, they'll get exposed by the Node Runtime Environment that's running your Next JS App through /api/my-file-name and it works almost the same way it would when coding an Express microservice. This means that while you can consume an endpoint in an endpoint, you will also "serve" (data, business logic...) through one or various HTTP methods.

On the other hand, when you fetch data from within a frontend component you're just consuming and endpoint. This endpoint can be one of your /api/whatever or an external one indistinctly.

This way you can code an API-first monolith with Next JS straight away. If you need to scale it in the future you should be able to grab the code inside /api/, put them on a different repo -or package inside the same monorepo if that's the case-, handle the dependencies one by one and finally deploy them isolated on different VPS, K8s pods or whatever it is you're using to deploy your Apps bits and pieces.

There are differences also between Next JS with pages directory and Next JS with app directory so knowing which one are you using would help in that scenario, either way it would be just for the deep details, the rest of this comment is valid in both scenarios.

Collapse
 
mohiyaddeen7 profile image
mohiyaddeen7

I totally agree with him. If you had doubts about whether to fetch the data inside the page component or API directory, then my friend Joel has answered your question quite well.

Collapse
 
mohiyaddeen7 profile image
mohiyaddeen7

one of the main benefits of using API routes in Next.js is the ability to perform server-side rendering (SSR), which can greatly improve SEO by providing search engines with pre-rendered HTML content. This is particularly beneficial for static or server-rendered pages.

However, when it comes to external APIs providing dynamic content, SSR alone may not make that content SEO-friendly. This is because external APIs typically serve data that is not directly under your control, and search engines may not index this content as effectively as static or server-rendered content.

while external API data can pose challenges for SEO, there are strategies and techniques you can employ within your Next.js application to make this content more SEO-friendly. A combination of SSR, caching, metadata, and structured data can help improve the indexing of dynamic external content by search engines.

Collapse
 
basemsala7 profile image
Basem Salah

`// app/api/posts

import { NextResponse } from 'next/server'

export async function GET() {
const res = await fetch('jsonplaceholder.typicode.com/posts', {
headers: {
'Content-Type': 'application/json',
'API-Key': process.env.DATA_API_KEY,
},
})
const data = await res.json()

return NextResponse.json({ data })

}

// in app page
const page = async () => {
const data = await fetch("api/posts")
return (


{data.map(post =>

{post.name}

)}

);
};

export default page;
`

Collapse
 
joelbonetr profile image
JoelBonetR ๐Ÿฅ‡ • Edited

In this example

// app/api/posts
import { NextResponse } from 'next/server';

export async function GET() {
  const res = await fetch('jsonplaceholder.typicode.com/posts', {
    headers: {
      'Content-Type': 'application/json',
      'API-Key': process.env.DATA_API_KEY,
    },
  });
  const data = await res.json();

  return NextResponse.json({ data });
}
Enter fullscreen mode Exit fullscreen mode
// in app page
const page = async () => {
  const data = await fetch('api/posts');
  return data?.map((post) => {
    post.name;
  });
};
export default page;
Enter fullscreen mode Exit fullscreen mode

You are proxying the fetch of jsonplaceholder.typicode.com/posts through an endpoint. It's almost the same than doing:

// in app page
const page = async () => {
  const data = await fetch('jsonplaceholder.typicode.com/posts', {
    headers: {
      'Content-Type': 'application/json',
      'API-Key': process.env.DATA_API_KEY,
    },
  });
};
export default page;
Enter fullscreen mode Exit fullscreen mode

and not having the app/api/posts part.
Differences being that in this second example, there's one "network jump" less (which is good), but anyone using the client side of the App could read your API Key (which is bad).

Now, you can add business logic in app/api/posts, maybe store some data into a DB with an ORM like Sequelize or similar, do some checks, accept a given subset of HTTP verbs and so on and so forth for it to fully make sense.

Here we're mixing Frontend and Backend stuff together -which is not bad in any way shape or form- it just requires you to have at least surface knowledge on both worlds.

Maybe a step by step guide, course or so can help you in your learning process.

If you are a self-taught dev (or in progress to be one) I would like to recommend you a book called "Computer Science: An Overview" which will give you the big picture. It's not about Next JS but about all CS niches.

In parallel you can keep learning Next JS (backend + frontend) along databases (PostgreSQL is a good start as it's one of the most used by companies).

Best regards

Thread Thread
 
basemsala7 profile image
Basem Salah

thank you for explaining in detail

Collapse
 
basemsala7 profile image
Basem Salah

and call api direct in page

Collapse
 
basemsala7 profile image
Basem Salah

ok i know this benefit ssr and pre-rendering .
i understand that nextjs is full stack framework that i can use API route to connect with the database and handle all business logic as a back end doing ..

so what is the difference between the following ..