Using Next.js with TypeScript

Learn via video courses
Topics Covered

Overview

Next.js is an open-source React framework used for building single-page web applications. It has various out-of-the-box functionalities that we can use to develop web applications faster, as a result, provides refined and elegant developer and user experiences. It is used majorly used to build landing pages, SEO-friendly websites, eCommerce Stores, and all kinds of web applications that need fast, high-performance load times.

Introduction

Next js TypeScript is considered a full-stack framework, templating languages, and extension tools. These two are combined to provide a better experience to the user and the developer both. Every developer hates bugs like typos or trying to access or use undeclared variables. TypeScript is used to catch and resolve these bugs during the development phase, and this is one of the significant features when integrating with a tool like Next.js.

What is Next.js?

Next.js is a production-ready, open-source React-based framework developed by Vercel. It is very fast and SEO-friendly and comes with server-side rendering capability. It enables search engines to easily optimize React-based apps with no configuration. It is a framework that allows the user to build a react app by rendering the content in advance on the server.

It is used to build both static and dynamic apps as Next.js supports both client and server-side rendering. It can pre-render pages at the build time, which can make your app faster because the browser doesn't have to spend time executing a JavaScript bundle to generate HTML for your app, which makes it possible for more search engine crawlers to index your app, which in turn better for SEO.

What is TypeScript?

TypeScript is an object-oriented programming language that was developed by Microsoft in 2012. TypeScript is considered the superset of JavaScript. TypeScript extends the functionality of JavaScript by adding data types, classes, and other object-oriented features with type-checking.

JavaScript is well suited for small-scale applications but TypeScript is used for large-scale applications. TypeScript can be used to develop JavaScript applications for both server-side and client-side execution. TypeScript programs consist of modules, functions, variables, comments, and expressions like a fully-fledged programming language.

The Next.js Functionalities

Various Next.js functionalities make the app productive and efficient when used in our project. Some of them are :

API Routes

Next.js supports API routes that let the user create an API endpoint as a Node.js serverless function. We can do this by creating a function inside the pages/api directory that has the following given format :

These functions are deployed as serverless functions also termed Lambdas.

File-System Routing

Next.js supports a file-system-based router that is built on the concept of pages. When a file is added to the pages directory, it is available as a route by default. The files inside the pages directory are used to define the most common patterns.

Index Routes :

The router will route the files named index to the root of the directory automatically.

  • pages/index.js -> /
  • pages/blog/index.js -> /blog

Nested Routes :

The router supports nested files. If we create a nested folder structure, files will automatically be routed.

  • pages/blog/post1.js -> /blog/post1
  • pages/dashboard/settings/user.js -> /dashboard/settings/user

Image Optimization

The Next.js image component next/image is an extension of the HTML <img> element, that is evolved for the modern web. Some optimizations built into the image component includes :

  • Improved Performance :
    Always serve correctly sized images for our device, using modern image formats.
  • Faster Page Loads :
    Images are loaded when they enter the viewport with optional blur-up placeholders.
  • Asset Flexibility :
    For the images stored on remote servers, image resizing is available on-demand basis.

Using the Image Component :

To add an image to our application, import the next/image component :

Now, we can define the src for our image either locally or remotely.

Middlewares

Middleware allows us to run the code before the request has been completed, then based on the incoming request, we can modify the response by rewriting, redirecting, modifying request or response headers, or responding directly. It runs before the cached content, so we can personalize static files and pages.

Using Middleware :

We will use middleware by using the following steps :

  1. Install the latest version of Next.js :

  2. Create a middleware.ts file at the root or in the src directory.

  3. Export a middleware function from the middleware.ts file.

ES Modules Support & URL Imports

URL import is an experimental feature that allows us to import modules directly from external servers. To opt-in, we need to add the allowed URL prefixes inside next.config.js :

Then, we can import the modules directly from URLs :

URL Imports can be used where normal package imports are used.

Server Components

The server components allow us to build applications that span the server and the client further combining the rich interactivity of client-side apps with the improved performance of traditional server rendering. In Next.js, we can use the app/ directory that uses server components.

HTTP Streaming

Streaming allows us to incrementally render the parts of our UI to the client. In Next.js, we can start using the app/ directory to take the advantage of HTTP streaming server rendering.

Next.js Live

Next.js live is also known as the preview mode in which we can pre-render a page at build time (Static generation) using getStaticProps and getStaticPaths. Static generation is important when our pages fetch data from a headless CMS. It's not ideal when we are writing a draft on our headless CMS and want to preview the draft immediately on the page.

Then Next.js will render these pages at the request time instead of the build time and fetch the draft content instead of the published content. It uses preview mode to solve this problem.

Using TypeScript in a Next.js App

In this section, we will learn to use TypeScript in a Next.js App.

There are two ways to add TypeScript in a Next.js app, that depends on the use case of the user :

Add TypeScript Using reate-next-app CLI :

Creating next.js application : The steps to create the application are given below :

  • We can add TypeScript when the next.js app is created by adding the -typescript or -ts flag in the create-next-app CLI. The command is given below :

    The project structure of the next.js app will look as shown below :

    project-structure-of-the-next-js-app

    The -typescript flag will install ESLint in your project.

    The package.json file will contain all the dependencies and dev dependencies installed.

    project-structure-of-the-next-js-app-2

    eslint and eslint-config-next are required to run ESLint in our app. @types/node, @types/react, and @types/react-dom are type definitions used to specify respective packages.

    So, now we can start creating our TypeScript files that end with the .ts or .tsx extension as per the needs of the user.

Add TypeScript to an Existing Project :

Add TypeScript to the app : Below are given steps to add TypeScript to our existing Next.js project.

  • Step - 1 :
    Create a tsconfig.json file. Every TypeScript project should have a tsconfig.json file that has all the configurations of the project. Create a tsconfig.json file by entering the command below at the root directory of your Next.js project in your terminal. By default, the file will be empty.

  • Step - 2 :
    Install the dependencies by entering the below command in the terminal.

  • Step - 3 :
    Populate the tsconfig.json after installing all the dependencies and run the below command :

    The above command will populate the file with some basic configurations. These configurations can be changed as per the user's requirements. Add the moduleResolution rule below if it is not present in the tsconfig file.

  • Step - 4 :
    Rename the extensions of the Javascript files from .js to .ts. Change the extensions of pages and components from .js/.jsx to .tsx.

    changing-js-to-ts

    After the necessary changes, the project structure will look like the above image.

Creating TypeScript Types in Next.js

We can create types for anything in our Next.js TypeScript app that includes prop types, API responses, and arguments for your utility functions.

In the above snippet, we have created a type named IPost. The interface expects name, id, and body properties.

Creating Components in Next.js

We can create our components in our Next.js TypeScript app. In the below given example, we will be going to create an increment/decrement counter. Consider the code snippet of index.tsx given below in the pages folder of the project. Here, the type of state counter is specified as a number.

Now we will create a new folder named components that will be our first component inside the pages folder and we will create a file named IncDecButton.tsx in components.

Here, props have to be of type IProps as we have As a developer, we need to know how important tests are for any production-level projects. Writing the tests can be time-consuming, but this will help us, in the long run, to solve problems in the codebase. We can also integrate these tests into the GitHub actions, as whenever we deploy to production or someone makes a pull request, then tests will run automatically and we will be notified of any failed tests.

After performing all the steps in the above sections, our app is ready to be tested on the browser window. We will begin by locating the root of the project and running the command :

If everything works as expected, we can see our next.js app with TypeScript at http://localhost:3000/.

Conclusion

  • Jest is an amazing inbuilt tool to test React-based apps. Since Next.js released v12, it has the jest configuration inbuilt powered by the Rust compiler.
  • Next.js has really good support for TypeScript and it is easy to set up which ensures the easy building of strongly typed react apps with Next.js and TypeScript that run on either client or server side.
  • Next.js TypeScript uses automatic code-splitting (lazy loading) to render only the JavaScript needed for our app.
  • Client-side data fetching is useful in Next.js TypeScript when our page doesn't require SEO Indexing.
  • Some of the important features of TypeScript include Type Inference, Static Typing, Static Null Checking, and Interoperability.
  • To test a Next.js TypeScript app, we should have a working knowledge of testing applications, React.js, Next.js, A code editor, and Node.js installed in our machine.