Server-Side Rendering is a technique that is often used to increase the performance and SEO of the pages rendered in a web app. The markup is generated on the server and then output the browser in HTML. This allows for search engines like Google to properly index URLs within your application. In this tutorial, we will go over how to use React.js SSR(Sever-Side-Rendering) with Next.js and Typescript. If you’re interested in learning more, click here to watch some of our videos on React development.

Next.js Setup

First, we’ll have to create a new project using the create-next-app command

$ npx create-next-app next-example

Now under the pages folder, change the index.js file to index.tsx and try to run the applications. You’ll run into the error ‘It looks like you’re trying to use TypeScript but do not have the required package(s) installed.‘.

Next Typescript Error

Next Typescript Error

To fix this, you must add typescript as a dependency.

yarn add --dev typescript @types/react @types/node

Now you should be able to run the application using npm run dev.

Nextjs initial page

Nextjs initial page

Rendering Server Data

Now that the project is setup, we’re going to want to display data on the screen. This data will come from a Rest API but because it’s using SSR, it can be detected by search engines on the initial load. You can do this by a method called getInitalProps. This loads data into the component before the initial page load and allows for you the generate HTML to display in the browser.

In this example, we’ll load a user profile. We’ll create an interface that represents some user data.

interface User {
  id: number;
  name: string;
  username: string;
}

Inside of our Home component, we’ll add the getInitialProps method. We will also add isomorphic-unfetch in order to make fetch requests server-side.

yarn add isomorphic-unfetch
Home.getInitialProps = async () => {
  const userContent: User = await fetch(
    `https://jsonplaceholder.typicode.com/users/1`
  ).then(r => r.json())

  return { userContent }
}

Now inside of the component, use the userContent prop to display the user information.

const Home = ({ userContent }) => (
  <div>
    <Head title='Home' />
    <Nav />

    <div className='hero'>
      <h1 className='title'>Welcome {userContent.name}</h1>
      <p className='description'>
        Username: {userContent.username}
      </p>
    </div>
)

Now when you run the app, you should get back HTML generated by the server.

Next SSR USer Profile

Next SSR USer Profile

Conclusion

Using Server Side Rendering with React.js is pretty straight forward. Many of the benefits such as increased and page load and page load times make it a great choice for client-facing apps. If you’re interested in video training on  React.js and Rest API development, please click this link to gain access.

Codebrains Newsletter

Get weekly dev news and tutorials.

Powered by ConvertKit