Learn more about Typescript in NextJS
This is a cheat sheet repository for Typescript in NextJS
npx create-next-app APP-NAME --typescript
npx create-next-app APP-NAME --typescript --eslint
Create a tsconfig.json
file in the root of the project (touch tsconfig.json
)
NextJS will automatically detect and configure this file for you after you run
npm run dev
ornpm run build
Alternatively, you can:
npm install --save-dev typescript @types/react @types/node
- Remember to add the @ alias for the root folder in
jsconfig.json
ortsconfig.json
:
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
// Use @ as an alias for the root directory
"@/*": ["./*"]
}
}
}
Remember also to rename your files from
.js
to.ts
and.tsx
- Strict mode is turned off by default in NextJS, when you feel comfortable with Typescript you can turn it on by adding the following to your
tsconfig.json
file:
{
"compilerOptions": {
"strict": true
}
}
- Static Site Generation (SSG) and Server-side Rendering (SSR)
import { GetStaticProps, GetStaticPaths, GetServerSideProps } from 'next'
export const getStaticProps: GetStaticProps = async (context) => {
// ...
}
export const getStaticPaths: GetStaticPaths = async () => {
// ...
}
export const getServerSideProps: GetServerSideProps = async (context) => {
// ...
}
- API Routes
import type { NextApiRequest, NextApiResponse } from 'next'
export default function handler(req: NextApiRequest, res: NextApiResponse) {
res.status(200).json({ name: 'John Doe' })
}
- Custom App
import type { AppProps } from 'next/app'
export default function MyApp({ Component, pageProps }: AppProps) {
return <Component {...pageProps} />
}