Next.js | Create a new project with Typescript

Next.js, Typescript

Next.js is becoming very popular in front-end ecosystem due the extra features that this framework adds in React and I absolutely recommend to use if you want this features bellow in your application:

  • Server Side Rendering: Keep the User Experience of. a Single Page Application but ensure that Search Engines can reach your application with all api requests information in your site.
  • Static Site Generation: keep some shared information that can need some api request saved in server to ensure to use backend only if is necessary.

By the end of this reading you'll be able to start. an Next.js application with. typescript configuration.

01: Starting a Next Application

In your terminal run this command bellow:

yarn create next-app <your-app-name>

02: Removing unnecessary folders

Now, lets remove some unnecessary files and folders

  • api folder
  • styles folder
  • all files in public folder

Let's keep the index.js and _app.js clean:

// index.js
export default function Home() {
   return (
      <>
         <h1>Hello world</h1>
      </>
   )
}
//_app.js
function MyApp({ Component, pageProps }) {
   return <Component {...pageProps} />
}

export default MyApp

03: Installing Typescript library

In your terminal run this command bellow to install React types and Typescript:

yarn add typescript
yarn add @types/react -D

Now, rename _app.js and index.js to _app.tsx and index.tsx respectively

Folders organized inside src

In your _app.tsx lets add types in properties

import { AppProps } from 'next/app';  
function MyApp({ Component, pageProps }: AppProps) {
   return <Component {...pageProps} /> 
}  

export default MyApp

Next.js create your typescript configuration file automatically when you try to run your project in your terminal

yarn dev

Now, we have our Next.js with Typescript configured! 'Hello world' and great job!

sample hello world page