Quick Guide to Next.js with TypeScript — Part 2

In part 1 we covered setting up newNext.js app with TypeScript with a basicNext.js page and a component.

In part 2, we are going to render some data on page

Next.js is known for it’s ability to bring server-side-rendering to your app with almost zero effort. We are going to use getServerSideProps from Next.js to fetch users list from a public JSON API to render on the page.
Along with getServerSideProps there are several methods to fetch data with Next.js but we are going to be using getServerSideProps in this part.

Open your Home.tsx and update it with code below

As you can see we are importing interface from a non-existent directory named types/types.ts Go ahead and create types.ts under types directory and enter following code in it. These are our custom interfaces to fit our user model.

We have added data fetching logic in our home page now that sends users array down props through getServerSideProps . We are iterating over this array and rendering Next.js Link to a slug based page. We don’t have that page yet. So, let’s go ahead and create one.

Next.js has smart routing that picks up pages and data passing via query params works out of the box. Looking at our <Link href={`/user/${id}`}>{name}</Link our slug based page will need to be inside a directory named user like this pages/user/[slug].tsxand enter code below in it.

and you have successfully built a tiny but strictly typed Next.js app with Next.js pages and React components.

TypeScript, GraphQL, React, Next.js