Anjali Ariscrisnã
Admilson Cruz

13 mars 2023

Min Read

Utilisation de Next.js avec TypeScript

Logo NEXT.JS plus wordmark TypeScript sur blanc, montrant comment Next.js TypeScript s'assemble.

Next.js est un framework open source conçu pour fonctionner avec React. Il est utilisé pour créer des pages de destination, des sites Web optimisés pour le référencement, des boutiques de commerce électronique et toutes sortes d'applications Web nécessitant des temps de chargement rapides et performants. D'autre part, Tapez Script est un langage de programmation basé sur JavaScript, supporté par Next.js. Ces deux éléments combinés offrent une meilleure expérience à la fois pour l'utilisateur et pour le développeur.

Next.js et TypeScript sont principalement classés dans la catégorie des frameworks complets, des langages de création de modèles et des outils d'extensions, respectivement, mais regardons quoi et comment les deux sont appliqués et comment ils peuvent travailler ensemble, y compris des exemples de son application.

blue arrow to the left
Imaginary Cloud logo

What is the Next.js framework?

Next.js is an open-source framework created by Vercel. It claims to be the Web's Software Development Kit with all the tools needed "to make the Web. Faster" (sic). Learn about Next.js features with React and its applications here.

What is Next.js used for?

Next.js lets search engines optimise React apps with very little setup on your part. Picture what a traditional React app sends first: a shell of an HTML page with nothing rendered inside it.

The browser then fetches the JavaScript file carrying your React code, renders content into the DOM, the browser's live tree of page elements, and makes it interactive. That works. It also has two drawbacks worth taking seriously:

  • The content is not reliably indexed by all search engines or read by social media link bots. Google's own documentation explains why JavaScript-rendered pages need a second processing pass before they are indexed.
  • It can take longer to reach the first contentful paint, the moment the browser paints the first piece of real content on screen rather than a blank shell.

Next.js lets you build a React app but render the content in advance on the server, so the first thing a user or a search bot sees is the fully rendered HTML. Once that initial page lands, client-side rendering takes over and the app behaves like any other React app.

Fully rendered content for bots. Highly interactive content for users. One codebase.

Client-side data fetching using the Next.js framework

Data fetching is where the Next.js framework earns its keep, because it can run several server rendering strategies from a single project.

Client-side fetching suits pages that do not need SEO indexing, do not need pre-rendered data, or change too often to be worth freezing. Static generation, also called pre-rendering, builds your pages once at build time rather than on every request. Here is the client-side version:

import { useEffect, useState } from 'react';

type Todo = { id: number; text: string; done: boolean };

export default function TodoList() {
  const [isLoading, setIsLoading] = useState(true);
  const [todos, setTodos] = useState<Todo[]>([]);

  useEffect(() => {
    fetch('/api/todos')
      .then((response) => response.json())
      .then((data: Todo[]) => {
        setTodos(data);
        setIsLoading(false);
      });
  }, []);

  if (isLoading) return <p>Loading...</p>;

  return (
    <ul>
      {todos.map((todo) => (
        <li key={todo.id}>{todo.text}</li>
      ))}
    </ul>
  );
}

That is client-side data fetching using React's useEffect hook. We initialise two constants, one to track whether the fetch is still pending and one to hold the result, then call useEffect with two arguments:

  • Callback — the function holding the side-effect logic that runs right after changes are pushed to the DOM. Here, that logic fetches data from an endpoint and saves it into our constant.
  • Dependencies — an array specifying when the callback should run. An empty array means run it once.

One detail worth catching. That Todo[] annotation on the response is a promise, not a guarantee: it tells the compiler what you expect the endpoint to send back, and nothing checks it at runtime. Later on we type the API route itself, so the promise is enforced at both ends.

blue arrow to the left
Imaginary Cloud logo

Qu'est-ce que Next.js ?

Next.js est un framework open source créé par Vercel. Il prétend être le kit de développement logiciel du Web avec tous les outils nécessaires « pour créer le Web ». Plus vite » (sic). Découvrez les fonctionnalités de Next.js avec React et ses applications ici.

Pour quoi Next.js est-il utilisé ?

Next.js permet aux moteurs de recherche d'optimiser facilement les applications React sans aucune configuration. Une application React traditionnelle est rendue côté client où le navigateur commence par une coque de page HTML dépourvue de contenu rendu. À partir de là, le navigateur récupère le fichier JavaScript contenant le code React pour afficher le contenu de la page et la rendre interactive. Cependant, il existe deux principaux inconvénients du rendu côté client:

1. Le contenu n'est pas indexé de manière fiable par tous les moteurs de recherche ou lu par des robots de réseaux sociaux ;‍2. L'accès à la première page contenant du contenu peut prendre plus de temps lorsqu'un utilisateur accède pour la première fois à la page Web.

Next.js est un framework qui vous permet de créer une application React mais rendre le contenu à l'avance sur le serveur Ainsi, la première chose qu'un utilisateur ou un robot de recherche voit est le code HTML entièrement rendu. Après avoir reçu cette page initiale, le rendu côté client prend le relais et fonctionne comme une application React traditionnelle. C'est le meilleur des deux mondes : un contenu entièrement rendu pour les robots et un contenu hautement interactif pour les utilisateurs.

Récupération de données côté client à l'aide de Next.js

La vraie magie entre en jeu lorsque nous parlons de récupération de données car Next.js peut exécuter plusieurs stratégies de rendu de serveur à partir d'un seul projet. La récupération de données côté client est utile lorsque votre page ne nécessite pas d'indexation SEO, lorsque vous n'avez pas besoin de pré-afficher vos données ou lorsque le contenu de vos pages doit être mis à jour fréquemment. La génération statique ou le pré-rendu vous permet de rendre vos pages au moment de la création. Consultez l'exemple ci-dessous.

undefined

Il est possible de voir dans l'extrait de code précédent un exemple de récupération de données côté client à l'aide du undefined hook de React.

Tout d'abord, nous avons initialisé des constantes pour vérifier si la récupération est toujours en attente et pour enregistrer les données résultant du processus de récupération. Ensuite, nous appelons undefined hook avec 2 arguments différents :

  • Rappel - fonction contenant le login des effets secondaires qui s'exécute juste après que les modifications aient été transmises au DOM. Dans notre cas, la logique consiste à récupérer les données d'un terminal et à les enregistrer dans notre constante.‍
  • Dépendances - un tableau de dépendances qui permet de spécifier quand le rappel doit être exécuté. En passant un tableau vide, cela signifie que nous voulons que le rappel ne s'exécute qu'une seule fois.
blue arrow to the left
Imaginary Cloud logo

Qu'est-ce que TypeScript ?

TypeScript est un langage de programmation développé et maintenu par Microsoft, et il s'agit d'un sur-ensemble strict de JavaScript. Il prend en charge le typage statique et dynamique et fournit en outre des fonctionnalités d'héritage, des classes, des étendues de visibilité, des espaces de noms, des interfaces, des unions et d'autres fonctionnalités modernes. TS a été conçu pour gérer des projets de plus grande envergure car il est plus facile de refactoriser le code. Apprenez-en plus sur ses fonctionnalités grâce à une comparaison approfondie avec JavaScript.

blue arrow to the left
Imaginary Cloud logo

Pourquoi utilisez-vous TypeScript ?

Il existe de nombreuses raisons pour lesquelles un développeur JavaScript envisage d'utiliser TypeScript :

  • Utilisation des nouvelles fonctionnalités d'ECMAScript - TypeScript prend en charge les normes ECMAScript et les transpile vers les cibles ECMAScript de votre choix, afin que vous puissiez utiliser des fonctionnalités telles que les modules, les fonctions lambda, les classes, la restructuration, entre autres.‍
  • Typage statique - JavaScript est un type dynamique qui ne sait pas quel est le type de variable tant qu'elle n'est pas réellement instanciée au moment de l'exécution ; ici, TypeScript ajoute la prise en charge des types au JavaScript.‍
  • Inférence de type - TypeScript rend la saisie un peu plus facile et beaucoup moins explicite grâce à l'utilisation de l'inférence de type. Même si vous ne saisissez pas explicitement les types, ils sont toujours là pour vous éviter de faire quelque chose qui, autrement, entraînerait une erreur d'exécution.‍
  • Meilleure prise en charge de l'IDE - L'expérience de développement avec TypeScript constitue une nette amélioration par rapport à JavaScript. Il existe une large gamme d'IDE offrant une excellente prise en charge de TypeScript, comme Visual Studio et VS Code, IntelliJ et Sublime, ou WebStorm.‍
  • Vérification stricte des valeurs nulles - Des erreurs telles que « vous ne pouvez pas lire une propriété « x » si elle n'est pas définie » sont courantes dans la programmation JavaScript. Vous pouvez éviter la plupart de ces types d'erreurs grâce à une vérification stricte, car il est impossible d'utiliser une variable inconnue du compilateur TypeScript.‍
  • Interopérabilité - TypeScript est étroitement lié à JavaScript et possède donc d'excellentes capacités d'interopérabilité, mais un travail supplémentaire est nécessaire pour travailler avec les bibliothèques JavaScript dans TypeScript.
Bannière « 18 bonnes pratiques agiles du cycle logiciel » : une femme tenant des post-it pour une appli SaaS.
blue arrow to the left
Imaginary Cloud logo

Comment installer TypeScript dans NextJS ?

Voici un guide étape par étape pour installer TypeScript dans une application Next.js :

1. Créer un projet de base - commande : undefined.Créez un projet à l'aide d'un modèle de base.

2. Ajouter undefined à la racine du projet pour activer TypeScript.

3. Structurez le projet dans le formulaire.

undefined

4. Création de types TypeScript dans Next.js

Vous pouvez créer des types pour n'importe quel élément de votre application, y compris les types d'accessoires, les réponses d'API, les arguments des fonctions, etc.

Nous créons d'abord un type pour notre undefined:

undefined

5. Création de composants dans Next.js

Maintenant que nous avons notre undefined type, nous pouvons créer le undefined composant.

undefined

Comme vous pouvez le voir, nous commençons par importer le type précédent que nous avons créé et en créons un autre appelé undefined, qui reflétera les accessoires reçus en tant que paramètres par le composant.

Ce composant est chargé d'afficher undefined objet. Ce composant reçoit le undefined objet, un undefined fonction, et une undefined fonctionnent comme des accessoires. Notez que cet argument doit correspondre au type d'accessoires pour satisfaire Typescript.

Créons maintenant notre undefined composant, responsable de l'ajout undefined dans notre application.

undefined

Notre composant accepte les undefined en tant que paramètre. Il gère la soumission d'un nouveau undefined. Si la valeur n'est pas vide, nous appelons le undefined fonction sur ce texte de tâche, puis définissez à nouveau la valeur du formulaire pour qu'elle soit vide. Ce composant renvoie un formulaire qui accepte les tâches et comporte un bouton d'envoi. En cliquant sur ce bouton, nous ajoutons la tâche à la liste des tâches.

6. Créez notre page afin d'utiliser nos composants de réaction.Nous allons commencer par importer les composants et les types que nous avons créés précédemment.

Après avoir importé les composants et les types, nous avons importé undefined, qui est fourni par Next.js, ce qui nous permet de définir le type sur la méthode getStaticProps.

Après cela, nous avons initialisé notre undefined à l'aide du undefined hook, en passant en argument nos tâches initiales fournies par le undefined.

Enfin, nous avons déclaré nos principales fonctions qui implémentent notre logique :

  • undefined - permet d'ajouter un todo dans notre liste
  • undefined - permet de supprimer une chose à faire dans notre liste
  • undefined - permet de définir une tâche comme terminée dans notre liste

À la fin, nous renvoyons une liste de nos todos, en utilisant nos composants.

Bannière de développement web et mobile : écran isométrique et application smartphone avec le logo React.

Vous avez trouvé cet article utile ? Ceux-ci vous plairont peut-être aussi !

blue arrow to the left
Imaginary Cloud logo

The App Router and TypeScript

Everything above uses the Pages Router. Since Next.js 13 the App Router has been the default for new projects, and as of Next.js 16 (October 2025) it is the standard the framework is built around — Turbopack is now the default bundler and the minimum is Node.js 20. The typing model shifts with the App Router. Starting a project today? This is the version to write.

Three things move:

  • Pages become server components. A page in app/ runs on the server by default and can be an async function, so data fetching happens inline. No getStaticProps, no props object to type: you type what you fetch, where you fetch it.
  • API routes become route handlers. pages/api/todos.ts becomes app/api/todos/route.ts, exporting a function named after the HTTP method and using the Web Request and Response objects rather than the Next.js-specific ones.
  • Caching replaces the rendering-mode choice. getStaticProps with revalidate becomes an option on the fetch call itself. The same shared type still spans both ends.

What changed in Next.js 16

If you last touched Next.js around the 13 or 14 releases, three things are worth knowing before you upgrade. Turbopack is now the default bundler for both dev and build, so cold starts and rebuilds are markedly faster and most projects without a custom webpack config need no changes. The minimum supported Node.js version is 20. And the caching model is now explicit: fetch is no longer cached by default, so you opt in per call with cache and next.revalidate rather than relying on framework defaults. None of this changes the typed-contract pattern in this article — types/todo.ts is still the single definition both ends share — but it does change the commands you run. The upgrade codemod (npx @next/codemod@latest upgrade latest) handles most of the mechanical work; budget your time for the App Router migration and React 19 compatibility, not the version bump itself.

// app/api/todos/route.ts
import { NextResponse } from 'next/server';
import { Todo } from '@/types/todo';

const todos: Todo[] = [
  { id: 1, text: 'Type the route handler', done: true },
  { id: 2, text: 'Ship it', done: false },
];

export async function GET() {
  return NextResponse.json<Todo[]>(todos);
}
// app/page.tsx
import TodoItem from '@/components/TodoItem';
import { Todo } from '@/types/todo';

async function getTodos(): Promise<Todo[]> {
  const response = await fetch('http://localhost:3000/api/todos', {
    next: { revalidate: 60 },
  });
  return response.json();
}

export default async function Home() {
  const todos = await getTodos();

  return (
    <ul>
      {todos.map((todo) => (
        <li key={todo.id}>{todo.text}</li>
      ))}
    </ul>
  );
}

Same contract as before: types/todo.ts is the single definition, the route handler declares it returns that shape, the page declares it consumes it. One caveat before you migrate anything. Interactive components like TodoForm need the 'use client' directive at the top of the file, because state and event handlers cannot run on the server.

blue arrow to the left
Imaginary Cloud logo

Frequently asked questions

Is Next.js worth using with TypeScript?

For any application you expect to maintain beyond a few months, yes. Next.js has first-class TypeScript support built in, so the setup cost is close to zero, and the type safety pays back on every refactor and every new developer who joins the project.

Can I add TypeScript to an existing Next.js project?

Yes, and you can do it incrementally. Add a tsconfig.json file, run the dev server, and Next.js installs what it needs. With allowJs set to true, your existing .js files keep working while you convert files to .tsx one at a time.

Does TypeScript slow down Next.js builds?

Type checking adds time to the build, but Next.js does not type check in the dev server's hot reload path, so day-to-day development is unaffected. On large codebases you can move the check to a separate CI step with tsc --noEmit and keep the build itself fast.

Do I need TypeScript for a small Next.js site?

Probably not. A landing page or a short-lived campaign site rarely lives long enough to repay the setup and the annotation effort. The line falls at whether the codebase will be handed to someone who did not write it.

What is the difference between getStaticProps and getServerSideProps?

getStaticProps runs at build time and produces HTML once, which suits content that changes rarely. getServerSideProps runs on every request, which suits content that is personalised or changes constantly. Both are fully typed in TypeScript. On the App Router, both are replaced by caching options on fetch.

Should I use the App Router or the Pages Router with TypeScript?

Use the App Router for anything new, because it is the default and where the framework is heading. Keep an existing Pages Router codebase where it is unless you have a reason to move: both are supported, and they can coexist in the same project during a migration.

blue arrow to the left
Imaginary Cloud logo

Putting the Next.js framework and TypeScript to work

The setup cost is a tsconfig.json file and the discipline of typing your props. The return arrives on the third refactor, on the first new joiner, and on the first API change that would otherwise have shipped broken.

So run the outlives test on your own project before you commit. If the answers point at a codebase somebody else will maintain, the pairing pays for itself. If they point at a prototype, save yourself the effort and the marker pen.

If you are weighing this up for a product your team has to live with, we are happy to talk it through. We build web products on this stack — from the Geo Matrix Decision Engine for Aurora Analytica, a Next.js platform that lets clinical-research teams run trial-design scenarios on their own data, to AppTweak's dashboard, where rebuilding in React and TypeScript cut loading time by 80%. We'll give you a straight answer about whether the pairing fits yours.

blue arrow to the left
Imaginary Cloud logo
Anjali Ariscrisnã
Anjali Ariscrisnã

Un spécialiste du marketing de croissance polyvalent et axé sur les données, doté d'une connaissance approfondie des affaires et informé des derniers développements dans le paysage du marketing numérique.

Read more posts by this author
Admilson Cruz
Admilson Cruz

Un développeur jeune et passionné qui cherche à faire une différence dans la façon dont les gens mènent leur vie quotidienne.

Read more posts by this author

People who read this post, also found these interesting:

Dropdown caret icon