Project Set Up

Course: Next.js Authentication and Authorization

Introduction

Now that you have an idea of how the authentication flow works, let's go and get your project set up.

Installing Next.js

To set up your project type the following command into your terminal and run it:

npx create-next-app@latest

Go ahead and name your project. We'll also be using ESLint, Tailwind CSS, a src directory, the App Router, Turbopack, and will NOT be customizing the import alias. This is a summary of our options:

√ What is your project named? ... my-app
√ Would you like to use TypeScript? ...  Yes
√ Which linter would you like to use? » ESLint
√ Would you like to use Tailwind CSS? ...  Yes
√ Would you like your code inside a `src/` directory? ...  Yes
√ Would you like to use App Router? (recommended) ... Yes
√ Would you like to use Turbopack? (recommended) ...  No
√ Would you like to customize the import alias (`@/*` by default)? ... No 

Installing Prisma

Now that Nextjs is configured, we will need to install Prisma. Go ahead and run the following commands in your console:

npm i -D prisma
npm install @prisma/client
npx prisma init

Note: In schema.prisma file, we may need to remove the output from generator Client.

After Prisma has been installed, we'll need to hook up our database to our project. For this project, we will be using Neon. You can sign up for a free account at neon.com. They have a generous free tier for you to work with.

Create a new project, and in the dashboard, click "connect". Go to the .env tab and copy and paste the contents to your .env file. It should read something like:

DATABASE_URL='postgresql://neondb_owner…'

Install Iron Session

To install iron-session, run the following in your terminal

npm i iron-session

Implement Singleton Pattern for Prisma

In your src directory, create a lib folder. Inside that lib folder, and in there create a db.ts file and copy the contents of the following into that file:

import { PrismaClient } from "@prisma/client"

declare global {
  var prisma: PrismaClient | undefined
}

export const db = globalThis.prisma || new PrismaClient()

if (process.env.NODE_ENV !== "production") {
  globalThis.prisma = db
}

The reason we need to implement this code is because Next.js uses hot reloading, which reloads affected files without restarting the server. Every time that happens, a new PrismaClient is created, which can lead to the app or database crashing.

So what we've done is implement global caching to ensure that only one database connection is used. Basically, if a PrismaClient is already active, we use it, otherwise make a new PrismaClient.

This only needs to be done in development since we don't hot reload in production.

With everything set up, we can start designing the database.