0
0
NextJSframework~5 mins

Server-side state passing in NextJS

Choose your learning style9 modes available
Introduction

Server-side state passing lets your Next.js app send data from the server to the page before it shows up. This helps show fresh info right away without waiting for the browser to ask for it.

You want to show user info right when the page loads, like a profile page.
You need to fetch data from a database or API before showing the page.
You want better SEO by sending content from the server.
You want to avoid loading spinners by having data ready on page load.
Syntax
NextJS
export async function getServerSideProps(context) {
  // fetch or prepare data here
  const data = 'some data';
  return {
    props: { data }, // pass data as props to the page
  };
}

export default function Page({ data }) {
  return <div>{data}</div>;
}

getServerSideProps runs on the server for every request.

The returned props object is sent to the page component as props.

Examples
This example sends a simple message from the server to the page.
NextJS
export async function getServerSideProps() {
  return { props: { message: 'Hello from server!' } };
}

export default function Page({ message }) {
  return <h1>{message}</h1>;
}
This example fetches data from an API on the server and passes it to the page.
NextJS
export async function getServerSideProps() {
  const res = await fetch('https://api.example.com/data');
  const data = await res.json();
  return { props: { data } };
}

export default function Page({ data }) {
  return <pre>{JSON.stringify(data, null, 2)}</pre>;
}
Sample Program

This page shows the current server time when the page loads. The time is fetched on the server and passed as a prop.

NextJS
export async function getServerSideProps() {
  const currentTime = new Date().toLocaleTimeString();
  return { props: { currentTime } };
}

export default function TimePage({ currentTime }) {
  return (
    <main>
      <h1>Current Server Time</h1>
      <p>The time when this page was loaded is: {currentTime}</p>
    </main>
  );
}
OutputSuccess
Important Notes

getServerSideProps runs on every request, so it can slow down your page if it does heavy work.

Use server-side state passing when you need fresh data on each page load.

Remember this only works in page components, not in regular React components.

Summary

Server-side state passing sends data from the server to the page before it shows.

Use getServerSideProps to fetch or prepare data on the server.

This helps show fresh data immediately and improves SEO.