DEV Community

Cover image for Server-Side Rendering
Suhas Palani
Suhas Palani

Posted on

Server-Side Rendering

Server-Side Rendering with Next.js

In this post, I'll dive into server-side rendering (SSR) with Next.js, a powerful React framework that makes it easy to create SSR applications. I'll cover the basics of SSR, set up a Next.js project, and explore how to create and deploy SSR applications.

1. Introduction to Server-Side Rendering (SSR)

What is Server-Side Rendering (SSR)?

Server-Side Rendering is a method of rendering web pages on the server instead of in the browser. This can improve performance, especially for the initial load, and enhance SEO since search engines can index the content more easily.

Benefits of SSR:

  • Improved Performance: Faster initial page load times.
  • Better SEO: Search engines can index the fully rendered content.
  • Enhanced User Experience: Users see the complete content more quickly.

2. Introduction to Next.js

Next.js is a popular React framework that provides built-in support for SSR, static site generation (SSG), and many other features.

Key Features of Next.js:

  • File-based Routing: Organize routes using the filesystem.
  • API Routes: Build API endpoints as serverless functions.
  • Static Site Generation (SSG): Generate static pages at build time.
  • Automatic Code Splitting: Optimize bundle size by splitting code automatically.

3. Setting Up a Next.js Project

Prerequisites:

  • Node.js and npm/yarn installed.

Steps to create a new Next.js project:

npx create-next-app@latest my-nextjs-app
cd my-nextjs-app
npm run dev
Enter fullscreen mode Exit fullscreen mode

Project Structure Overview:

  • pages/: Directory for page components.
  • public/: Directory for static files.
  • styles/: Directory for global and component-specific styles.

4. Creating Your First Page

Create an index.js file inside the pages/ directory:

// pages/index.js
import Head from 'next/head';

export default function Home() {
  return (
    <div>
      <Head>
        <title>My Next.js App</title>
      </Head>
      <h1>Welcome to Next.js!</h1>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • Head: Component to manage the document head.
  • Basic structure of a Next.js page component.

5. Server-Side Rendering in Next.js

Using getServerSideProps for SSR:

Example of fetching data on the server side:

// pages/index.js
import Head from 'next/head';

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

  // Pass data to the page via props
  return { props: { data } };
}

export default function Home({ data }) {
  return (
    <div>
      <Head>
        <title>My Next.js App</title>
      </Head>
      <h1>Welcome to Next.js!</h1>
      <pre>{JSON.stringify(data, null, 2)}</pre>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • getServerSideProps: Fetches data at request time.
  • Data is passed to the page component as props.

6. Static Site Generation (SSG)

Using getStaticProps for SSG:

Example of generating static pages at build time:

// pages/index.js
import Head from 'next/head';

export async function getStaticProps() {
  // Fetch data from an API
  const res = await fetch('https://api.example.com/data');
  const data = await res.json();

  // Pass data to the page via props
  return { props: { data } };
}

export default function Home({ data }) {
  return (
    <div>
      <Head>
        <title>My Next.js App</title>
      </Head>
      <h1>Welcome to Next.js!</h1>
      <pre>{JSON.stringify(data, null, 2)}</pre>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • getStaticProps: Fetches data at build time.
  • Suitable for pages with static content or content that doesn't change often.

7. Dynamic Routing and SSG

Creating Dynamic Routes:

Example of dynamic routing with SSG:

// pages/posts/[id].js
import Head from 'next/head';

export async function getStaticPaths() {
  // Fetch list of posts
  const res = await fetch('https://api.example.com/posts');
  const posts = await res.json();

  // Get the paths we want to pre-render based on posts
  const paths = posts.map((post) => ({
    params: { id: post.id.toString() },
  }));

  // We'll pre-render only these paths at build time.
  return { paths, fallback: false };
}

export async function getStaticProps({ params }) {
  // Fetch data for a single post
  const res = await fetch(`https://api.example.com/posts/${params.id}`);
  const post = await res.json();

  // Pass post data to the page via props
  return { props: { post } };
}

export default function Post({ post }) {
  return (
    <div>
      <Head>
        <title>{post.title}</title>
      </Head>
      <h1>{post.title}</h1>
      <p>{post.body}</p>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • getStaticPaths: Defines dynamic routes to be generated at build time.
  • getStaticProps: Fetches data for each route.

8. API Routes in Next.js

Creating an API Route:

Example of creating an API route:

// pages/api/hello.js
export default function handler(req, res) {
  res.status(200).json({ message: 'Hello, world!' });
}
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • API routes allow building serverless functions directly within the Next.js application.

9. Best Practices for Next.js and SSR

Best Practices:

  • Use getServerSideProps for frequently changing data.
  • Use getStaticProps for static content for better performance.
  • Optimize images and use lazy loading.
  • Secure sensitive data and avoid exposing it in client-side code.

10. Conclusion

Summarize the key points covered:

  • Introduction to SSR and its benefits.
  • Setting up and creating pages with Next.js.
  • Using getServerSideProps and getStaticProps.
  • Creating dynamic routes and API routes.
  • Best practices for SSR with Next.js.

11. Additional Resources

Top comments (0)