Next.js - Typescript
Next.js - TypeScript Integration
Section titled “Next.js - TypeScript Integration”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.
Initializing a TypeScript Project
Section titled “Initializing a TypeScript Project”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 --typescriptAlternatively, 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.jsonfile with sensible defaults. - Generates basic project files using
.tsand.tsxextensions (e.g.,app/layout.tsx,app/page.tsx).
Adding TypeScript to an Existing Project
Section titled “Adding TypeScript to an Existing Project”If you have an existing JavaScript Next.js project, you can add TypeScript support manually:
- Create an empty
tsconfig.jsonfile in your project root:
touch tsconfig.json- Install the required dependencies:
npm install --save-dev typescript @types/react @types/node- Run the development server:
npm run devNext.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.
- You can now start renaming your
.js/.jsxfiles to.ts/.tsxand adding types.
Example: Typed Page Component
Section titled “Example: Typed Page Component”Here’s how a simple page component looks in TypeScript (app/about/page.tsx):
import { Metadata } from 'next';
// Optional: Define metadata for the pageexport 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> );}Example: Typed API Route (Route Handler)
Section titled “Example: Typed API Route (Route Handler)”Route Handlers (the App Router equivalent of API Routes) also benefit greatly from TypeScript. Create app/api/hello/route.ts:
import { NextResponse } from 'next/server';
// Define the expected structure of the response datainterface 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.
Verify API Route
Section titled “Verify API Route”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!"}