Setup Next.js application with Typescript

October 28, 2020

Install Next.js app with npx

npx create-next-app hello-next

Rename javascript files to .ts and tsx

Your files that contain jsx will become .tsx and the ones with plain javascript are renamed to .ts.

  • pages/api/hello.js -> hello.ts
  • pages/_app.js -> _app.tsx
  • pages/index.js -> index.tsx

jsx and tsx

Create tsconfig.json

In the root folder of the Nextjs application create an empty tsconfig.json:

tsconfig.json for nextjs

npm install typescript support and save it as a dev dependency

  • typescript
  • @types/node
  • @types/react
$ npm i typescript @types/node @types/react -D

+ @types/react@16.9.55
+ typescript@4.0.5
+ @types/node@14.14.6
added 5 packages from 72 contributors and audited 810 packages in 3.619s

45 packages are looking for funding
  run `npm fund` for details

found 3 low severity vulnerabilities
  run `npm audit fix` to fix them, or `npm audit` for details

startup the dev server

At this time if we look at the index.tsx file, it’s going to be all red, no problems. Just issue npm run dev in the terminal and next will recognixe the tsconfig.json and will populate it for your Typescript base Nextjs project.

$ npm run dev

> hello-next@0.1.0 dev /home/darvat/dev/react/hello-next
> next dev

ready - started server on http://localhost:3000
We detected TypeScript in your project and created a tsconfig.json file for you.

event - compiled successfully
Attention: Next.js now collects completely anonymous telemetry regarding usage.
This information is used to shape Next.js' roadmap and prioritize features.
You can learn more, including how to opt-out if you'd not like to participate in this anonymous program, by visiting the following URL:
https://nextjs.org/telemetry

You have now converted your Nextjs project to Typescript. Check it out on the Nextjs default server port on http://localhost:3000

add _document.tsx to control the webapp’s high level layout and inject specific tags

As mentioned on the [Next.js portal(https://nextjs.org/docs/advanced-features/custom-document)]:

A custom Document is commonly used to augment your application’s <html> and <body> tags.

A very minimal _document.tsx - that must reside in /pages - is like this (just added meta description for demo purposes):

import Document, { Html, Head, Main, NextScript } from 'next/document'

class MyDocument extends Document {

  render() {
    return (
      <Html>
        <Head>
          <meta name="description" content="awesome site description"/>
        </Head>
        <body>
          <Main />
          <NextScript />
        </body>
      </Html>
    )
  }
}

export default MyDocument

Hope this helps. emoji-thumbsup