Next.js

Created: Getting Started with Next.js

Updated: 03 September 2023

Introduction

Next.js is framework for building single page applications using React, Next.js allows us to use a combination of SSR and Prerendering to build our applications based on the data requirements

Notes from Next.js Documentation. This is slightly different to the documentation because I am using a Typescript setup

Setting Up

To set up a new Next.js application we will need install the relevant dependencies

1
mkdir web
2
cd web
3
yarn init -y
4
yarn add react react-dom next typescript @types/react @types/node

Then, add the following to your package.json file:

1
"scripts": {
2
"dev": "next",
3
"build": "next build",
4
"start": "next start"
5
}

Now, we can create the pages/index.tsx with the following function component:

pages/index.tsx

1
import { NextPage } from 'next'
2
3
const Index: NextPage = () => <h1>Hello world!</h1>
4
5
export default Index

And then run yarn dev to start the Dev server. You should be able the index page on http://localhost:3000

Linking Pages

We can first create a new page about.tsx in the pages directory:

about.tsx

1
import { NextPage } from 'next'
2
3
const About: NextPage = () => <h1>About</h1>
4
5
export default About

We can then create a link from our index page to link to this using the next/link component. Modify the index page to do this like so:

index.tsx

1
import { NextPage } from 'next'
2
import Link from 'next/link'
3
4
const Index: NextPage = () => (
5
<>
6
<h1>Hello world!</h1>
7
<p>
8
<Link href="/about">
9
<a>About</a>
10
</Link>
11
</p>
12
</>
13
)
14
export default Index

The Link is a wrapper component which only accepts an href, any other attributes needed for our link need to be included in the a component

Shared Components

Like you would expect from when we use React on its own we can create shared components. Components are created in the components directory. We’ll create a header and layout component and implement this on our pages

Header.tsx

1
import Link from 'next/link'
2
import { NextPage } from 'next'
3
4
const Header = () => (
5
<div>
6
<Link href="/">
7
<a>Home</a>
8
</Link>
9
<Link href="/about">
10
<a>About</a>
11
</Link>
12
</div>
13
)
14
15
export default Header

We can then create a Layout component which works as a higher order component (HOC) to render the overall page layout given a Page Component:

Layout.tsx

1
import { NextPage } from 'next'
2
import Header from './Header'
3
4
const Layout = ({ children }) => (
5
<>
6
<Header></Header>
7
{children}
8
</>
9
)
10
11
export default Layout
12
13
export const withLayout = (Page: NextPage | NextPage<any>) => {
14
return () => (
15
<Layout>
16
<Page />
17
</Layout>
18
)
19
}

We can then implement the withLayout function when exporting out relevant page components:

index.tsx

1
export default withLayout(Index)

about.tsx

1
export default withLayout(About)

Dynamic Pages

Query Params

We can create dynamic pages based on the data from the URL Query parameters a user has when visiting the page. We can update the index page to have a list of posts that we will link to:

index.tsx

1
import { NextPage } from 'next'
2
import Link from 'next/link'
3
import { withLayout } from '../components/Layout'
4
5
const PostLink = ({ title }) => (
6
<li>
7
<Link href={`/post?title=${title}`}>
8
<a>{title}</a>
9
</Link>
10
</li>
11
)
12
13
const Index: NextPage = () => (
14
<>
15
<h1>Hello world!</h1>
16
<p>
17
<Link href="/about">
18
<a>About</a>
19
</Link>
20
</p>
21
<ol>
22
<PostLink title="First Post"></PostLink>
23
<PostLink title="Second Post"></PostLink>
24
<PostLink title="Third Post"></PostLink>
25
</ol>
26
</>
27
)
28
29
export default withLayout(Index)

We can then make use of the useRouter hook to retrieve this from a post page like so:

post.tsx

1
import { NextPage } from 'next'
2
import { useRouter } from 'next/router'
3
import { withLayout } from '../components/Layout'
4
5
const Post: NextPage = () => {
6
const router = useRouter()
7
8
return <h1>Post: {router.query.title}</h1>
9
}
10
export default withLayout(Post)

Route Params

Usually we may want to link to specific pages on our site and the above method of using query params for everything is not ideal, we can also set up dynamic urls such that a post’s url will be something like /post/post_id for example. Next.js allows us to build our routes using our folder structure as well as a special syntax for the filenames. For example a page like above may be in file like pages/post/[id].tsx

We can update our index page to make use of this routing strategy by updating the PostLink to use an id:

index.tsx

1
import { NextPage } from 'next'
2
import Link from 'next/link'
3
import { withLayout } from '../components/Layout'
4
5
const PostLink = ({ id }) => (
6
<li>
7
<Link href="/post/[id]" as={`/post/${id}`}>
8
<a>{id}</a>
9
</Link>
10
</li>
11
)
12
13
const Index: NextPage = () => (
14
<>
15
<h1>Hello world!</h1>
16
<p>
17
<Link href="/about">
18
<a>About</a>
19
</Link>
20
</p>
21
<ol>
22
<PostLink id="First-Post"></PostLink>
23
<PostLink id="Second-Post"></PostLink>
24
<PostLink id="Third-Post"></PostLink>
25
</ol>
26
</>
27
)
28
29
export default withLayout(Index)

The href is the link to the page as per our component setup, and the as is the url to show in the browser

post/[id].tsx

1
import { NextPage } from 'next'
2
import { useRouter } from 'next/router'
3
import { withLayout } from '../../components/Layout'
4
5
const Post: NextPage = () => {
6
const router = useRouter()
7
8
return <h1>Post: {router.query.id}</h1>
9
}
10
export default withLayout(Post)

Note how this is almost exactly like in the previous case where we used the query parameter to populate our page but now we use the id

Fetching Page Data

To fetch data we’ll use isomorphic-unfetch which works on both the browser and on the client side. We need to add this to our application:

1
yarn add isomorphic-unfetch

Wherever we need to use this we can simply import it with:

1
import fetch from 'isomorphic-unfetch'

Next we’ll create a basic page which displays the content from the tvmaze api so that we have something to render. Update the Header component to link to the tv page that we will create after

Header.tsx

1
import Link from 'next/link'
2
import { NextPage } from 'next'
3
4
const Header = () => (
5
<div>
6
<Link href="/">
7
<a>Home</a>
8
</Link>
9
<Link href="/about">
10
<a>About</a>
11
</Link>
12
<Link href="/tv">
13
<a>TV</a>
14
</Link>
15
</div>
16
)
17
18
export default Header

We can then create a new pages/tv.tsx file with the following component:

tv.tsx

1
import { NextPage } from 'next'
2
import Layout, { withLayout } from '../components/Layout'
3
import fetch from 'isomorphic-unfetch'
4
5
type ShowData = {
6
id: string
7
name: string
8
}
9
10
type TvResponse = {
11
show: ShowData
12
}[]
13
14
type TvData = {
15
data: ShowData[]
16
}
17
18
const Tv: NextPage<TvData> = (props) => {
19
return (
20
<Layout>
21
<h1>TV</h1>
22
<ul>
23
{props.data?.map((show) => (
24
<li key={show.id}> {show.name} </li>
25
))}
26
</ul>
27
</Layout>
28
)
29
}
30
31
export default Tv

Note how in the above we make use of the Layout component as a normal component instead of the wrapper, this is because the getInitialProps function is only called directly from the page component and so this doesn’t work if we use the withLayout function like we have above

Next, we will need to update our page’s getServerSideProps function which is an async function that NextPages use to fetch data on the server side, this is called by the framework to get the properties for the page when rendering

tv.tsx

1
export const getServerSideProps: GetServerSideProps = async () => {
2
const res = await fetch('https://api.tvmaze.com/search/shows?q=batman')
3
const data = (await res.json()) as TvResponse
4
5
console.log(`Show data fetched. Count: ${data.length}`)
6
7
return {
8
props: {
9
data: data.map((el) => el.show),
10
},
11
}
12
}

Styling

For styling components next.js has a few different methods to style components, for the moment my preferred way of doing this is using CSS Modules. To create and use a module we need to do the following:

First create a Module for the component’s CSS, this is just a normal CSS selector with the .module.css extension. This essentially scopes the CSS

Header.module.css

1
.Header a {
2
color: red;
3
}

Next, in our tsx we need to import the module like so:

Header.tsx

1
import styles from './Header.module.css'

Thereafter we can make use of the different classes exposed in our module by assigning the className attribute of a component to a a property of the imported style

1
const Header = () => <div className={styles.Header}>...</div>

If instead of locally scoped styles we would like to use global styles we need to create a pages/_app.tsx file and import any stylesheets we need globally into that, the purpose for this all being in a single file is to avoid conflicting global styles

_app.tsx

1
import '../styles.css'
2
import { AppProps } from 'next/app'
3
4
const MyApp = ({ Component, pageProps }: AppProps) => {
5
return <Component {...pageProps} />
6
}
7
8
export default MyApp

API Routes

API Routes are found in the pages/api directory. These are simple functions which handle the relevant API Route

For a route without any parameter like the api/data route we can have:

pages/api/data.tsx

1
import { NextApiRequest, NextApiResponse } from 'next'
2
3
type Data = {
4
name: string
5
}
6
7
export default (req: NextApiRequest, res: NextApiResponse<Data>) => {
8
res.status(200).json({ name: 'John Doe' })
9
}

Each API Endpoint has a request and response of NextApiRequest and NextApiResponse respectively

We can then consume this API on the client. To do this instead of using a simple fetch we’ll use SWR (Stale while Revalidate) which enables us to fetch data much more efficiently than if we were to make a normal HTTP request by using the cache to use temporary data

Install swr with:

1
yarn add swr

Next, in our pages/index.tsx we need to define a fetcher function which will handle the fetching of data from the backend. This can be any asynchronous function which returns the data. We can also just pass in the fetch function to make a normal get request and take the response directly

1
const fetcher = async (url: string) => {
2
const res = await fetch(url)
3
return (await res.json()) as { name: string }
4
}

This will then be used by the useSWR hook in our component like so:

1
const { data, error } = useSWR('/api/data', fetcher)
2
3
let name = data?.name
4
5
if (!data) name = 'Loading...'
6
if (error) name = 'Failed to fetch data.'

Putting this all together in our index page we end up with the following

index.tsx

1
import { NextPage } from 'next'
2
import Link from 'next/link'
3
import { withLayout } from '../components/Layout'
4
import useSWR from 'swr'
5
6
const fetcher = async (url: string) => {
7
const res = await fetch(url)
8
return (await res.json()) as { name: string }
9
}
10
11
const PostLink = ({ id }) => (
12
<li>
13
<Link href="/post/[id]" as={`/post/${id}`}>
14
<a>{id}</a>
15
</Link>
16
</li>
17
)
18
19
const Index: NextPage = () => {
20
const { data, error } = useSWR('/api/data', fetcher)
21
22
let name = data?.name
23
24
if (!data) name = 'Loading...'
25
if (error) name = 'Failed to fetch data.'
26
27
return (
28
<>
29
<h1>Hello world!</h1>
30
<h2>{name}</h2>
31
<p>
32
<Link href="/about">
33
<a>About</a>
34
</Link>
35
</p>
36
<ol>
37
<PostLink id="First-Post"></PostLink>
38
<PostLink id="Second-Post"></PostLink>
39
<PostLink id="Third-Post"></PostLink>
40
</ol>
41
</>
42
)
43
}
44
45
export default withLayout(Index)

Run in Production

To run the application in production you simply need to build it with:

1
yarn build

And then start it with:

1
yarn start