#Next.js server side

1 messages · Page 1 of 1 (latest)

gritty mango
#

So based on next.js documentation: "Whenever possible, we recommend fetching data on the server with Server Components. This allows you to:

Have direct access to backend data resources (e.g. databases).
Keep your application more secure by preventing sensitive information, such as access tokens and API keys, from being exposed to the client.
Fetch data and render in the same environment. This reduces both the back-and-forth communication between client and server, as well as the work on the main thread on the client.
Perform multiple data fetches with single round-trip instead of multiple individual requests on the client.
Reduce client-server waterfalls.
Depending on your region, data fetching can also happen closer to your data source, reducing latency and improving performance."

How do I actually leverage server-side in practice?

swift groveBOT
#

Hi @gritty mango. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

In Next.js, you can leverage server-side rendering by using the getServerSideProps function. This function is called by the server on every request, allowing you to fetch data on the server and forward props to the default exported React component in the file. The initial HTML for the page is prerendered from the server, followed by "hydrating" the page in the browser (making it interactive).

Here's an example of how you can use getServerSideProps:

// `pages` directory
 
export async function getServerSideProps() {
 const res = await fetch(`<https://...`>)
 const projects = await res.json()
 
 return { props: { projects } }
}
 
export default function Dashboard({ projects }) {
 return (
 <ul>
 {projects.map((project) => (
 <li key={project.id}>{project.name}</li>
 ))}
 </ul>
 )
}

In this example, getServerSideProps fetches data from an external API and passes it to the Dashboard page as a prop. This function is run on every request instead of on build time, which means the data is always up-to-date.

You can also colocate your data fetching inside your React components using Server Components. This allows you to send less JavaScript to the client, while maintaining the rendered HTML from the server. Here's an example:

// `app` directory
 
// This function can be named anything
async function getProjects() {
 const res = await fetch(`<https://...`,> { cache: 'no-store' })
 const projects = await res.json()
 
 return projects
}
 
export default async function Dashboard() {
 const projects = await getProjects()
 
 return (
 <ul>
 {projects.map((project) => (
 <li key={project.id}>{project.name}</li>
 ))}
 </ul>
 )
}
#

In this example, the getProjects function fetches data from an external API and the data is used in the Dashboard component. By setting the cache option to no-store, the fetched data is never cached, similar to getServerSideProps in the pages directory.

For more information, you can check out the Next.js documentation on Server-side Rendering (https://nextjs.org/docs/pages/building-your-application/rendering/server-side-rendering) and Server Components (https://nextjs.org/docs/app/building-your-application/rendering/server-components).

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

#

@gritty mango kapa.ai is still learning and improving, please let us know how it did by reacting below

gritty mango
#

I am using app router and next.js 14, so not pages and getServerSideProps @swift grove

swift groveBOT
#

Let me check the knowledge base for you. One moment! :books:

#

In Next.js 14 with the App Router, the traditional data fetching methods like getServerSideProps and getStaticProps have been replaced with a simpler API built on top of fetch() and async React Server Components.

Here's an example of how you can fetch data in the app directory:

// `app` directory
 
// This function can be named anything
async function getProjects() {
 const res = await fetch(`<https://...`,> { cache: 'no-store' })
 const projects = await res.json()
 
 return projects
}
 
export default async function Dashboard() {
 const projects = await getProjects()
 
 return (
 <ul>
 {projects.map((project) => (
 <li key={project.id}>{project.name}</li>
 ))}
 </ul>
 )
}

In this example, the getProjects function fetches data from an external API and the data is used in the Dashboard component. By setting the cache option to no-store, the fetched data is never cached, similar to getServerSideProps in the pages directory.

For API routes, you can use the HTTP method names as the function names. Here's an example:

import { NextResponse } from "next/server";

export async function GET() {
  //SOME LOGIC TO GET THE DATA(This api was used with prisma orm)
  return new NextResponse.json([YOUR_DATA], { status: 200 });
}

export async function POST(Request) {
  //YOUR POST LOGIC
  return new NextResponse.json() 
}

In this example, the GET and POST functions handle GET and POST requests respectively.

For more information, you can check out the Next.js documentation on Data Fetching (https://nextjs.org/docs/app/building-your-application/data-fetching) and API Routes (https://nextjs.org/docs/app/api-reference/file-conventions/route).

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: