nextjs ssr in javascript

To use Next.js for server-side rendering (SSR) in JavaScript, follow these steps:

  1. Install Next.js in your project using npm or yarn:
npm install next
17 chars
2 lines

or

yarn add next
14 chars
2 lines
  1. Create a pages directory in your project root directory.

  2. Create a JavaScript file in the pages directory with the name of the route you want to create. For example, if you want to create a route for /about, create a file called about.js in the pages directory.

  3. In the JavaScript file, export a function called getServerSideProps which returns an object with the data to be used when rendering the component. This function will be called at runtime on the server-side before rendering the component.

index.tsx
export async function getServerSideProps() {
  // Fetch data from external API or database
  const res = await fetch('https://api.example.com/data');
  const data = await res.json();

  // Pass data to the page component as props
  return { props: { data } };
}
262 chars
9 lines
  1. Create a React component in the same JavaScript file which will be used to render the contents of the page. This component will receive the data fetched in the getServerSideProps function as props.
index.tsx
function About({ data }) {
  return (
    <div>
      <h1>About</h1>
      <p>{data}</p>
    </div>
  );
}

export default About;
130 chars
11 lines
  1. Start the Next.js development server using the dev command:
npm run dev
12 chars
2 lines

or

yarn dev
9 chars
2 lines
  1. View the page in your web browser at http://localhost:3000/about. The page will be rendered server-side with the data fetched and passed as props to the React component.

gistlibby LogSnag