<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Prateek Vijayvergiya</title>
    <description>The latest articles on DEV Community by Prateek Vijayvergiya (@prateekvijayvergiya).</description>
    <link>https://dev.to/prateekvijayvergiya</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F487296%2Ff56343cc-83ce-466b-984e-8001c8c9b90d.jpeg</url>
      <title>DEV Community: Prateek Vijayvergiya</title>
      <link>https://dev.to/prateekvijayvergiya</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/prateekvijayvergiya"/>
    <language>en</language>
    <item>
      <title>Server Side Rendering with Next.js</title>
      <dc:creator>Prateek Vijayvergiya</dc:creator>
      <pubDate>Sun, 11 Oct 2020 09:44:58 +0000</pubDate>
      <link>https://dev.to/prateekvijayvergiya/server-side-rendering-with-next-js-1896</link>
      <guid>https://dev.to/prateekvijayvergiya/server-side-rendering-with-next-js-1896</guid>
      <description>&lt;h1&gt;
  
  
  Prerequisites
&lt;/h1&gt;

&lt;p&gt;Basic understanding of React.js and Functional Programming Concepts.&lt;/p&gt;

&lt;h1&gt;
  
  
  Problem with Client Side rendering (CSR)
&lt;/h1&gt;

&lt;p&gt;React, Angular and Vue are used to create Single Page Applications (SPAs). But they all provide CSR means whole application is rendered on client side by browser. So due to this, rendering of our initial page will take some time.&lt;/p&gt;

&lt;p&gt;So to render our pages much faster we can use Next.js (Framework for React), which renders our pages on server side and give us pre-rendered HTML for our pages.&lt;/p&gt;

&lt;h1&gt;
  
  
  What is Server Side Rendering (SSR)
&lt;/h1&gt;

&lt;p&gt;When a user request a webpage, server prepares the page by fetching user-specific data and sends it to the user’s machine. The browser then construes the content and displays the page. This entire process of fetching data from the database, creating an HTML page and serve it to user is known as SSR.&lt;/p&gt;

&lt;h1&gt;
  
  
  How Next.js helps in SSR
&lt;/h1&gt;

&lt;p&gt;Next.js builds the HTML page at build time and serves the pre-rendered page from server to browser with minimal JavaScript code and when page is loaded by browser, its JavaScript code runs and makes the page fully interactive. (This Process is called &lt;strong&gt;Hydration&lt;/strong&gt;)&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fi8fxcroh8idof191d3cl.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fi8fxcroh8idof191d3cl.png" alt="Pre-rendering in Next.js"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;h1&gt;
  
  
  Two forms of pre-rendering
&lt;/h1&gt;

&lt;ol&gt;
&lt;li&gt;Static Generation (SSG): HTML is generated at build time.&lt;/li&gt;
&lt;li&gt;Server Side Rendering: HTML is generated on each user request.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;...&lt;/p&gt;
&lt;h1&gt;
  
  
  What are we going to build
&lt;/h1&gt;

&lt;p&gt;A Next.js application with SSG which shows list of users. This is a new feature of Next.js which is available in Next 9.0 and later versions. You can check the application &lt;a href="https://go-user-five.vercel.app/users" rel="noopener noreferrer"&gt;here&lt;/a&gt;. Complete source code can be found on &lt;a href="https://github.com/prateekvijayvergiya/go-user" rel="noopener noreferrer"&gt;Github&lt;/a&gt;.&lt;/p&gt;
&lt;h1&gt;
  
  
  So let’s build it.
&lt;/h1&gt;

&lt;p&gt;Create a new Next.js app using ‘create-next-app’ which sets up working environment with everything ready for you.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npx create-next-app
or
yarn create next-app
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h1&gt;
  
  
  External Libraries
&lt;/h1&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;a href="https://material-ui.com/" rel="noopener noreferrer"&gt;Material-UI&lt;/a&gt; - as a UI library&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://dummyapi.io/" rel="noopener noreferrer"&gt;Dummy-Api&lt;/a&gt; for some data&lt;/li&gt;
&lt;li&gt;Axios for AJAX calls&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Update your &lt;code&gt;_app.js&lt;/code&gt; like this to change the header of application.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React, {Fragment} from 'react'
import Head from 'next/head'
import '../styles/globals.css'
function MyApp({ Component, pageProps }) {
  return (
    &amp;lt;Fragment&amp;gt;
      &amp;lt;Head&amp;gt;
        &amp;lt;title&amp;gt;Go User&amp;lt;/title&amp;gt;
        &amp;lt;link rel="icon" href="/favicon.ico" /&amp;gt;
      &amp;lt;/Head&amp;gt;
      &amp;lt;Component {...pageProps} /&amp;gt;
    &amp;lt;/Fragment&amp;gt;
  )
}
export default MyApp
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now create a &lt;code&gt;lib&lt;/code&gt; folder at root of application and inside it create a file &lt;code&gt;users.js&lt;/code&gt;. Inside it export an async function &lt;code&gt;getAllUsers&lt;/code&gt; which will fetch list of users from Api.&lt;/p&gt;

&lt;p&gt;So your &lt;code&gt;lib/users.js&lt;/code&gt; will look like this&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import axios from 'axios'
import {BASE_URL, APP_ID} from './constants'
export const getAllUsers = async () =&amp;gt; {
  const users = await axios.get(
                `${BASE_URL}/user`,{headers:{'app-id': APP_ID}}
              )
  .then(({data}) =&amp;gt; {
    return data
  })
  return users
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here &lt;code&gt;BASE_URL&lt;/code&gt; will be &lt;code&gt;‘https://dummyapi.io/data/api'&lt;/code&gt; and you can get the unique &lt;code&gt;APP_ID&lt;/code&gt; from &lt;a href="https://dummyapi.io/" rel="noopener noreferrer"&gt;Dummy-Api&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Now create a folder &lt;code&gt;users&lt;/code&gt; inside pages folder, and file &lt;code&gt;index.js&lt;/code&gt; inside it.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Info&lt;/strong&gt;: Any folder or file inside pages folder will become a webpage automatically, so now you can access this page at path &lt;code&gt;/users&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Let’s create an async function &lt;code&gt;getStaticProps&lt;/code&gt; which provides props to the component on server side in &lt;code&gt;pages/users/index.js&lt;/code&gt;. This function will call our &lt;code&gt;getAllUsers&lt;/code&gt; and provide the list of users to the component to render.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Note&lt;/strong&gt;: Everything inside &lt;code&gt;getStaticProps&lt;/code&gt; will run on server.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export const getStaticProps = async () =&amp;gt; {
  const allUsers = await getAllUsers()
  return {
    props: {
      allUsers
    }
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now create a component which will render a card with individual user’s information provided to it as props.&lt;/p&gt;

&lt;p&gt;At root folder create components/card/index.js and it will look like this&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React from 'react'
import { makeStyles } from '@material-ui/core/styles'
import Card from '@material-ui/core/Card'
import CardActionArea from '@material-ui/core/CardActionArea'
import CardContent from '@material-ui/core/CardContent'
import CardMedia from '@material-ui/core/CardMedia'
import Typography from '@material-ui/core/Typography'
import styles from '../../styles/Card.module.css'
const UserCard = ({name, email, id, image}) =&amp;gt; {
  const classes = useStyles()
  return (
    &amp;lt;Card className={styles.root}&amp;gt;
      &amp;lt;CardActionArea&amp;gt;
        &amp;lt;CardMedia
          component="img"
          alt="user image"
          height="200"
          image={image}
        /&amp;gt;
        &amp;lt;CardContent&amp;gt;
          &amp;lt;Typography className={classes.text} gutterBottom
            variant="h5" component="h2"&amp;gt;
            {name}
          &amp;lt;/Typography&amp;gt;
          &amp;lt;Typography className={classes.text} variant="body2"
            color="textSecondary"&amp;gt;
            {email}
          &amp;lt;/Typography&amp;gt;
        &amp;lt;/CardContent&amp;gt;
      &amp;lt;/CardActionArea&amp;gt;
    &amp;lt;/Card&amp;gt;
  )
}
const useStyles = makeStyles({
  root: {
    maxWidth: 250,
    padding: 5
  },
  text: {
    textOverflow: 'ellipsis',
    whiteSpace: 'nowrap',
    overflow: 'hidden',
  }
})
export default UserCard
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Create a component &lt;code&gt;Users&lt;/code&gt; which will call our card component with user data. so updated &lt;code&gt;pages/users/index.js&lt;/code&gt; file look like this&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React from 'react'
import Grid from '@material-ui/core/Grid'
import { getAllUsers } from '../../lib/users'
import UserCard from '../../components/card'
const Users = ({allUsers}) =&amp;gt; {
  return (
    &amp;lt;Grid container spacing={5} justify="space-evenly"&amp;gt;
      {allUsers.data.map(({id, firstName, email, picture}) =&amp;gt; (
        &amp;lt;Grid item xs={6} lg={2} md={4} key={id}&amp;gt;
          &amp;lt;UserCard {...{name: firstName, id, email, image: 
             picture}}/&amp;gt;
        &amp;lt;/Grid&amp;gt;
       ))}
     &amp;lt;/Grid&amp;gt;
  )
}
export const getStaticProps = async () =&amp;gt; {
  const allUsers = await getAllUsers()
  return {
    props: {
      allUsers
    }
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here &lt;code&gt;getStaticProps&lt;/code&gt; fetch the list of users from Api on server side and pass them to &lt;code&gt;Users&lt;/code&gt; component as props. Then the whole component gets build on server itself and users data will be passed as &lt;code&gt;json&lt;/code&gt; file.&lt;/p&gt;

&lt;p&gt;Now build your application using &lt;code&gt;yarn dev&lt;/code&gt; and check out application at &lt;code&gt;http://localhost:3000/users&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;It will look like this&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fz8odtskh2ahp87p60o74.PNG" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fz8odtskh2ahp87p60o74.PNG" alt="List of Users"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;...&lt;/p&gt;

&lt;h1&gt;
  
  
  Is Next.js actually Building the application on server ?
&lt;/h1&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fyuijmis2tbdgnh8q388a.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fyuijmis2tbdgnh8q388a.jpg" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Modify the scripts object in &lt;code&gt;package.json&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;"scripts": {
  "build": "next build &amp;amp;&amp;amp; next export"
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now run &lt;code&gt;yarn build&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;You can actually see the pre rendered HTML pages on server inside the &lt;code&gt;.next/server/pages&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fyzlkdm7lflphwdya8wrx.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fyzlkdm7lflphwdya8wrx.png" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h1&gt;
  
  
  Summary
&lt;/h1&gt;

&lt;p&gt;We made a Next.js application and rendered list of users on server side. Pre-rendered HTML pages comes up for each page on browser. You can check out more about Next.js &lt;a href="https://nextjs.org/" rel="noopener noreferrer"&gt;here&lt;/a&gt;.&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>react</category>
      <category>nextjs</category>
    </item>
  </channel>
</rss>
