How to use Typescript to Build a Next.js Application

How to use Typescript to Build a Next.js Application

Learn how to use Typescript to build a Next.js application. Learn how to use TypeScript with Next.js. Next.js is a React framework that aims to provide the best development experience. Next.js is feature rich, including hybrid static and server rendering, TypeScript support, built-in CSS support, API routers, and much more. TypeScript is an open-source language that is built on JavaScript that allows developers to use types.

Learn how to use Typescript to build a Next.js application.

Next.js is a React framework that aims to provide the best development experience. It is feature rich, including hybrid static and server rendering, TypeScript support, built-in CSS support, API routers, and much more.

TypeScript is an open-source language that is built on JavaScript that allows developers to use types. In this tutorial, you will learn how to use TypeScript with Next.js.

Finally, you will secure your application with Okta Single Sign-On and the built-in functionality of Next.js, as well as the support of the next-auth package.

Create Your Okta Application

The first thing you will need to do is create an Okta developer account if you don’t have one already. The account is free, doesn’t require a credit card, and allows you to start with Okta immediately. Once you have signed up, log in to the Developer Console and click on Applications. Click Add Application and select Web. In your application settings screen set your URIs to localhost:3000 instead of the default localhost:8080. Next, set your Login redirect URIs to http://localhost:3000/api/auth/callback/okta. This is the default callback URI that next-auth will use. Give your application a meaningful name, I named mine NextJs. Click Done and you will be brought to your application’s management screen. Click on General and note your Client ID and Client secret as you will need these in your application.

Okta App Settings

Create Your Next.js Application

Open your favorite IDE. For this tutorial, I used Visual Studio Code. Navigate to the folder where you wish to keep your application. Next, use the create-next-app task runner by using the command npx create-next-app and follow the instructions. After the runner is complete, open the folder it created for you.

Since you are using TypeScript in this tutorial you will need to set up TypeScript support. Create a new file in the root of your application called tsconfig.json. Next.js will automatically populate this file with its default values but you can edit them if you wish. Next, run npm run dev in your console and you will see instructions about installing your dependencies for TypeScript.

To do this, open the console and run the following commands.

npm i [email protected]
npm i @types/[email protected]
npm i @types/[email protected]    

This will complete your TypeScript setup. But there are more dependencies you should add at this point. You can add next-auth at this point. Next-auth makes setting up any type of authentication in Next.js simple. Of course, for this application, you are only setting up Okta as an external provider. Install next-auth with the command below and you will see how to implement it later.

npm i [email protected]

Finally, for this tutorial, you will use Bootstrap for your CSS framework.

 npm i [email protected]

Convert Your Next.js Application to TypeScript

The task running for creating a Next.js application does not include an option for using TypeScript. Therefore you will need to manually convert your application from JavaScript to TypeScript. The process is simple and should only take a moment.

You have already completed the first two steps by setting up your tsconfig.json file and installing your dependencies. Now you will need to convert files with the .js extension to .tsx. You will need to do this for each file in your pages directory and any subdirectories. Any subsequent components you add will also need to have the .tsx file extension.

Set Up Your Authentication

Next, you’ll need to set up the authentication for external providers.

Before you can implement authentication, you will need to ensure that your .env.local file is set up correctly. Add this file to the root of your project if one doesn’t exist yet. Add the following values to it.

OKTA_CLIENTID={yourClientId}
OKTA_CLIENTSECRET={yourClientSecret}
OKTA_DOMAIN={yourOktaDomain}
NEXTAUTH_URL=http://localhost:3000

Now, under your pages\api folder create a new folder called auth if one doesn’t exist yet. Add a file called [...nextauth].ts. Add the following code to it.

import NextAuth from 'next-auth'
import Providers from 'next-auth/providers'

const options = {
  // Configure one or more authentication providers
  providers: [
    Providers.Okta({
      clientId: process.env.OKTA_CLIENTID,
      clientSecret: process.env.OKTA_CLIENTSECRET,
      domain: process.env.OKTA_DOMAIN
    }),
    // ...add more providers here
  ]
}

export default (req, res) => NextAuth(req, res, options)

Finally, open pages\_app.tsx and replace the existing code with the following.

import '../styles/globals.css'
import 'bootstrap/dist/css/bootstrap.min.css'

import { Provider } from 'next-auth/client'

function MyApp({ Component, pageProps }) {
  return (
    <Provider session={pageProps.session}>
      <Component {...pageProps} />
    </Provider>
  )
}

export default MyApp

This code is the default Next.js code wrapped in a Provider class from next-auth. The provider class makes sharing the session between pages easier. You added the Bootstrap CSS in this file as well. This will enable you to use Bootstrap on your pages.

Write Your Next.js Components and Pages

Your application is set up and ready to develop. Start by adding a new folder called Components to the root of your directory. This will be a folder for your shared components. Add a new file called Movies.tsx and add the following code.

export default function Movies() {

    return (
        <div className="row">

            <div className="col-lg-4">

                <div className="card">
                    <img className="card-img-top" src="https://images-na.ssl-images-amazon.com/images/I/91gDYZG%2BzDL._AC_SL1500_.jpg" alt="Card image cap"></img>
                    <div className="card-body">
                        <h5 className="card-title">Die Hard</h5>
                        <p className="card-text">He's the only chance anyone has got.</p>
                    </div>
                </div>

            </div>

            <div className="col-lg-4">

                <div className="card">
                    <img className="card-img-top" src="https://m.media-amazon.com/images/M/MV5BZjRlNDUxZjAt[email protected]._V1_.jpg" alt="Card image cap"></img>
                    <div className="card-body">
                        <h5 className="card-title">Die Hard 2</h5>
                        <p className="card-text">They say lightning never strikes twice... They were wrong</p>
                    </div>
                </div>

            </div>

            <div className="col-lg-4">

                <div className="card">
                    <img className="card-img-top" src="https://belgianfilmfreak.files.wordpress.com/2017/01/d0.jpg" alt="Card image cap"></img>
                    <div className="card-body">
                        <h5 className="card-title">Die Hard: With a Vengence</h5>
                        <p className="card-text">Think Fast, Look Alive, Die Hard</p>
                    </div>
                </div>

            </div>
        </div>
    )
}

typescript next react javascript web-development

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

How native is React Native? | React Native vs Native App Development

Article covers: How native is react native?, React Native vs (Ionic, Cordova), Similarities and difference between React Native and Native App Development.

Make an App with React JS / JavaScript: React and TypeScript

Building a Web Application as a Front-End Developer using React JS and TypeScript! Learn how to use the “Thinking in React” method and apply it to your real web application. We will be using real live weather data to display in our application and make our components reusable and maintainable.

Next.js vs. React: The Developer Experience

The developer experience for Next.js vs. React is similar in some ways and drastically different in others. In the world of React, Next.js has become a popular framework for “hitting the ground running.” Next.js builds on top of React to provide a streamlined development experience. There is definitely a different experience when building a project with Next.js vs. React.

How to Migrate a React Component from JavaScript to TypeScript

Learn how to easily migrate a React component from JavaScript to TypeScript to improve your project. When migrating over to TypeScript, one basic thing to keep in mind is TypeScript files have a .ts extension instead of .js. Another thing to keep in mind that makes migrating over a breeze is that you can configure your TypeScript compiler to allow JavaScript files.

Tendencias Javascript y Web 2020. React, Next.js, Deno

Tendencias Javascript y Web 2020. React, Next.js, Deno. En este video te voy a mencionar algunas herramientas y frameworks que fueron, seguirán siendo o van a ser tendencia en este 2020. Entre ellas están React, Next.js, Deno, los Headless CMS como Strapi, entre otros.