Building Server-Side Components in Next.js: A Step-by-Step Guide
Tags: react, nextjs, frontend, javascript
Published: 2023-01-09 19:12:07

This article was published in my [personal website](https://devsdepot.com), make sure to check it out: https://www.devsdepot.com/blog/server-side-components-in-nextjs

## Introduction

Next.js is a well-known JavaScript framework for developing server-side React apps. Next.js supports server-side components (SSCs), which allow developers to create reusable components that can be rendered on both the server and the client.

Server-side components have numerous advantages, including faster performance and improved search engine optimization (SEO). Next.js can build fully-formed HTML pages that can be given to the client faster and with more context for search engines to index by rendering components on the server.

We'll take a deep dive into the realm of Next.js server-side components in this article. We'll look at what server-side components are, how to make and use them in a Next.js project, and some advanced ways for using them. By the end of this article, you'll have a firm grasp on how to use server-side components to create better Next.js applications.

## Setting up a Next.js project

We must first create a Next.js project before we can begin working with server-side components. Here's how to go about it:

1. To begin, ensure that Node.js and npm (the Node.js package manager) are installed on your machine. You may verify this by typing node -v and npm -v into your terminal. If you don't already have Node.js and npm installed, you can get them from the official website.
2. In your terminal, create a new directory for your Next.js project and navigate to it.
3. To make a new Next.js project, use the following command:

```bash
npm init next-app
```

4. This will prompt you to give your project a name. Enter a name and press the Enter key.
5. Next.js will create a new project in the current directory and install any dependencies that are required. This could take some time.
6. Once the installation is complete, navigate to the project directory and run the following command to start the development server:

```bash
npm run dev
```

7. This will launch the development server and launch your Next.js application in a new browser window. A welcome message and a link to the Next.js documentation should appear.

Congratulations! You now have a working Next.js project. In the following part, we'll go over what server-side components are and how they work in the Next.js framework.

## What are server-side components?

Server-side components (SSCs) are an important element of the Next.js framework that enable developers to create reusable components that can be rendered on both the server and the client. SSCs are similar to standard React components, but they have a few key distinctions that make them ideal for server rendering.

Improved performance is one of the primary advantages of server-side components. Next.js may build fully-formed HTML pages that can be provided to the client faster, minimizing the time it takes for the page to load by rendering components on the server. This is particularly crucial for people with sluggish internet connections or for pages with a large amount of material that takes a long time to render on the client.

Search engine optimization can also benefit from server-side components (SEO). Next.js can provide more context about a website's content to search engines by rendering components on the server, making it easier for them to index and interpret the page. This can increase a page's rating in search results and attract more traffic to the site.

To use server-side components in a Next.js project, create a.server.js file for each component that will be rendered on the server. This file should include a method that accepts a list of props and returns a React element. When a page is requested, Next.js will execute this function and render the page on the server using the returned React element. The client will then pick up where the server left off and render the page on the client's behalf.

In the following part, we'll go over how to create and use server-side components in a Next.js project.

## Creating a server-side component

To add a server-side component to a Next.js project, establish a new directory for the component and add a `.server.js` file to it. This file should include a method that accepts a list of props and returns a React element.

Assume we want to make a server-side component called `MyComponent` that shows a greeting. Here's an example of a `.server.js` file for `MyComponent`:

```jsx
export default function MyComponent(props) {
  return (
    <div>
      <h1>Hello, {props.name}!</h1>
      <p>Welcome to my Next.js application.</p>
    </div>
  )
}
```

To use this component in a page, import it and render it like you would any other React component. To utilize `MyComponent` on a page called `index.js`, for example, you could perform the following:

```jsx
import MyComponent from './MyComponent.server.js'

export default function Index() {
  return (
    <div>
      <MyComponent name="World" />
    </div>
  )
}
```

When the page is requested, Next.js will invoke the `MyComponent` function and render the page on the server using the provided React element. The client will then pick up where the server left off and render the page on the client's behalf.

We'll look at some advanced approaches for working with server-side components in Next.js in the following section.

## Advanced techniques

To get the most out of server-side components in Next.js, you can employ a number of advanced strategies. Here are a couple such examples:

**Asynchronous data fetching**

One popular application for server-side components is asynchronous data fetching from an API or database. To accomplish this, use the `getServerSideProps` function in your pages to retrieve data from the server and provide it as props to your components.

Here's how to use `getServerSideProps` to fetch data for a server-side component:

```jsx
import MyComponent from './MyComponent.server.js'

export default function Index(props) {
  return (
    <div>
      <MyComponent {...props} />
    </div>
  )
}

export async function getServerSideProps() {
  const res = await fetch('http://localhost:8000/data')
  const data = await res.json()
  return { props: data }
}
```

When the page is requested, the `getServerSideProps` method on the server is called. It retrieves data from an API and returns it to the page as props. The data is subsequently passed to the `MyComponent` component as props by the page.

**Using server-side components with Next.js's built-in CSS support**

Next.js includes built-in support for styling components with CSS-in-JS libraries such as `styled-jsx`. To use this functionality with server-side components, wrap them in a `<style jsx>` element and import the `jsx` pragma at the top of your code.

Here's an example of how to use `styled-jsx` to style a server-side component:

```jsx
import { Fragment } from 'react'
import { jsx } from '@emotion/core'

export default function MyComponent(props) {
  return (
    <Fragment>
      <style jsx>{`
        h1 {
          color: red;
        }
      `}</style>
      <h1>Hello, {props.name}!</h1>
      <p>Welcome to my Next.js application.</p>
    </Fragment>
  )
}
```

The `<style jsx>` element is used in this example to build a CSS block that styles the h1 element with the color red.

I hope that these advanced strategies have given you some ideas for how to progress your server-side component development. We'll sum up this post with a few closing words in the following section.

## Conclusion

We've looked at Next.js server-side components and how they may be used to create high-performance, SEO-friendly applications in this article. We've gone over the fundamentals of generating and deploying server-side components in a Next.js project, as well as some advanced approaches like asynchronous data fetching and CSS-in-JS styling.

If you're new to Next.js and server-side components, I hope this post has given you a solid platform to work from. If you're already familiar with these ideas, I hope you've learnt something new and gotten some ideas for your next project.