is dynamic routes in Next JS rendered server-side or client-side?

so I'm working in a project that requires server-side rendering for SEO purposes, I'm using Next JS with react in my project.

I'm taking a dynamic routing tutorial on this link https://nextjs.org/learn/basics/clean-urls-with-dynamic-routing

I created a simple page to check if it's working or not

import Head from 'next/head'
import React, { Fragment } from 'react'
import { withRouter } from 'next/router'

class Product extends React.Component {
  render() {
    return (
      <Fragment>
        <Head />
        <h1>{this.props.router.query.name}</h1>
      </Fragment>
    )
  }
}

export default withRouter(Product)

I put that in /pages/product/[name].js and turn on the server in dev mode then visited localhost:3000/product/cheese

when the page loaded, I checked in "view source" on Chrome to check if it's rendered server-side or not but nothing on the code contains "cheese"

Am I doing it wrong? or the code is rendered client-side? any answer will be appreciated

1 answer

  • answered 2019-10-08 03:24 lakerskill

    import Layout from '../components/MyLayout';
    import Link from 'next/link';
    import fetch from 'isomorphic-unfetch';
    
    const Index = props => (
      <Layout>
        <h1>Batman TV Shows</h1>
        <ul>
          {props.shows.map(show => (
            <li key={show.id}>
              <Link href="/p/[id]" as={`/p/${show.id}`}>
                <a>{show.name}</a>
              </Link>
            </li>
          ))}
        </ul>
      </Layout>
    );
    
    Index.getInitialProps = async function() {
      const res = await fetch('https://api.tvmaze.com/search/shows?q=batman');
      const data = await res.json();
    
      console.log(`Show data fetched. Count: ${data.length}`);
    
      return {
        shows: data.map(entry => entry.show)
      };
    };
    

    As you will soon see, you will need to use getInitialProps for it to be server side rendered. Then this page will be created during the build, and will have all the applicable information in the view source. Will have SEO as well.

    When you run npm build, it will show you which is statically generated, and what is ssr. But you need to use getInitialProps otherwise it will be generated client side.