Skip to content

Next.js - Typescript

Next.js offers excellent built-in support for TypeScript, providing enhanced type safety and developer experience. Setting up a new project with TypeScript is straightforward.

The easiest way to start a new Next.js project with TypeScript is using create-next-app:

npx create-next-app@latest my-typescript-app --typescript

Alternatively, if you don’t specify --typescript, create-next-app will prompt you and ask if you want to use TypeScript. Selecting ‘Yes’ (the default) achieves the same result.

This command automatically:

  • Installs necessary TypeScript dependencies (typescript, @types/react, @types/node).
  • Creates a pre-configured tsconfig.json file with sensible defaults.
  • Generates basic project files using .ts and .tsx extensions (e.g., app/layout.tsx, app/page.tsx).

If you have an existing JavaScript Next.js project, you can add TypeScript support manually:

  1. Create an empty tsconfig.json file in your project root:
touch tsconfig.json
  1. Install the required dependencies:
npm install --save-dev typescript @types/react @types/node
  1. Run the development server:
npm run dev

Next.js will detect the tsconfig.json and the installed types. It will automatically populate tsconfig.json with recommended settings and create a next-env.d.ts file for Next.js type definitions.

  1. You can now start renaming your .js/.jsx files to .ts/.tsx and adding types.

Here’s how a simple page component looks in TypeScript (app/about/page.tsx):

app/about/page.tsx
import { Metadata } from 'next';
// Optional: Define metadata for the page
export const metadata: Metadata = {
title: 'About Us',
};
export default function AboutPage() {
const teamMembers: string[] = ['Alice', 'Bob', 'Charlie'];
return (
<main>
<h1>About Our Team</h1>
<ul>
{teamMembers.map((member) => (
<li key={member}>{member}</li>
))}
</ul>
</main>
);
}

Route Handlers (the App Router equivalent of API Routes) also benefit greatly from TypeScript. Create app/api/hello/route.ts:

app/api/hello/route.ts
import { NextResponse } from 'next/server';
// Define the expected structure of the response data
interface HelloResponse {
message: string;
}
export async function GET(request: Request): Promise<NextResponse<HelloResponse>> {
// You can access request details via the 'request' object if needed
// const { searchParams } = new URL(request.url);
// const name = searchParams.get('name');
const data: HelloResponse = {
message: 'Welcome from the API!'
};
return NextResponse.json(data);
}

Using TypeScript helps catch errors during development, improves code readability, and enables better tooling like autocompletion and refactoring.

Run npm run dev and navigate to http://localhost:3000/api/hello in your browser. You should see the JSON response:

{"message":"Welcome from the API!"}