Learn Next.js · 13/15

Authentication: Securing Your Application

9 min read

Authentication: Securing Your Application 🛡️

Welcome, intrepid developer, to the crucial world of authentication in Next.js! Think of your application as an exclusive club. Right now, the doors are wide open, and anyone can wander in, poke around, and maybe even graffiti your meticulously crafted database. Authentication is the friendly but firm bouncer at the door, checking IDs and ensuring only the right people get in.

In this guide, we'll demystify the process of securing your Next.js application. We'll start with the bouncer's basic training (authentication strategies) and then equip them with the best tools for the job (NextAuth.js). By the end, you'll be able to confidently protect your routes and data, ensuring a safe and personalized experience for your users.

1. Overview of Authentication Strategies in Next.js

Before we start building walls, let's survey the landscape. In the realm of Next.js, there are a few common ways to handle who gets in and who stays out.

The Problem: How do we verify a user's identity and then remember who they are as they navigate through different pages of our application?

The Solution: We need a system to check credentials and then issue some form of "access pass" that the user can present on subsequent requests. This is where different authentication strategies come into play.

Client-Side vs. Server-Side Authentication

Imagine you're checking into a hotel.

  • Client-Side Authentication: This is like the hotel giving you a keycard. You hold onto it, and every time you want to access your room (a protected page), you show the keycard. In web terms, the "keycard" is often a token (like a JWT) stored in the browser's local storage or cookies. When you want to access a protected part of the app, your browser sends this token along with the request.

    • Pros: Can feel faster for the user as the app can immediately render a loading state while it verifies the token in the background.
    • Cons: Can lead to a flash of unauthenticated content before the token is verified and the user is redirected. Storing tokens in local storage can also be vulnerable to cross-site scripting (XSS) attacks.
  • Server-Side Authentication: This is more like the hotel having a front desk that checks your ID every time you enter. Before a page is even sent to your browser, the server checks if you're allowed to see it.

    • Pros: More secure as sensitive information and session data are handled on the server. It also prevents the flash of unauthenticated content because the decision to show the page is made before it's rendered.
    • Cons: Can sometimes be slightly slower as there's a server check before the page is rendered.

Modern Next.js (with the App Router) heavily favors server-side authentication. It's generally more secure and provides a better user experience.

App Router vs. Pages Router Authentication

Next.js has two different ways of structuring your application's routes: the older "Pages Router" and the newer "App Router." While the core concepts of authentication are the same, the implementation details differ.

  • Pages Router: Authentication logic was often handled in special functions like getServerSideProps or in API routes.
  • App Router: The introduction of Server Components, Server Actions, and Middleware has made server-side authentication more streamlined and powerful. We can now check a user's session directly within our components on the server, and protect routes more efficiently with Middleware.

For this guide, we'll be focusing on the modern and recommended approach using the App Router.

2. Setting up NextAuth.js (Auth.js) v5

Manually building a secure authentication system is like trying to build your own car from scratch. It's possible, but you're likely to miss a few crucial safety features. That's where NextAuth.js (now officially part of the Auth.js project) comes in. It's a complete, open-source authentication solution for Next.js that handles all the complicated stuff for you.

The Problem: How do we implement a robust and secure authentication system without spending weeks reinventing the wheel and potentially introducing security vulnerabilities?

The Solution: Use a battle-tested library like NextAuth.js. It simplifies everything from social logins to session management.

Installation and Initial Setup

Let's get our hands dirty! We'll start by installing the necessary packages.

  1. Install NextAuth.js: Open your terminal in your Next.js project and run:

    bash
    npm install next-auth@beta

    We're using the @beta tag because this is the version designed for the App Router and is the future of the library.

  2. Create a Secret: NextAuth.js needs a secret key to encrypt its session information. You can generate a strong secret with the following command:

    bash
    npx auth secret

    This will create a .env.local file in your project root (if it doesn't exist) and add an AUTH_SECRET. Keep this secret safe and don't commit it to your version control.

  3. Configure Auth.js: Now for the heart of the setup. Create a new file named auth.ts (or .js) in the root of your project. This file will contain your main NextAuth.js configuration.

    typescript
    // auth.ts
    import NextAuth from "next-auth"
    import GitHub from "next-auth/providers/github"
    import Google from "next-auth/providers/google"
    
    export const { handlers, auth, signIn, signOut } = NextAuth({
      providers: [
        // We'll add our providers here in the next step
      ],
    })
  4. Create the API Route Handler: NextAuth.js needs a dedicated API route to handle authentication requests (like when a user is redirected from Google after logging in). Create the following folder structure and file: app/api/auth/[...nextauth]/route.ts.

    typescript
    // app/api/auth/[...nextauth]/route.ts
    import { handlers } from "@/auth" // a reference to our auth.ts file
    export const { GET, POST } = handlers

    This special file naming convention ensures that any request to /api/auth/... is handled by NextAuth.js.

With these steps, the basic foundation of NextAuth.js is in place. Now, let's give users a way to actually log in!

3. Implementing OAuth Providers: Google and GitHub Login

Why force users to create yet another password when they can log in with an account they already have and trust? This is the magic of OAuth.

The Problem: We want to offer users a convenient and secure way to sign in without them needing to create and remember a new password for our site.

The Solution: Integrate popular OAuth providers like Google and GitHub. NextAuth.js makes this incredibly simple.

Setting up Google and GitHub OAuth

First, you'll need to create an OAuth application on both Google Cloud Platform and GitHub to get your client ID and client secret. These are like a username and password for your application to communicate with Google and GitHub's authentication services.

  • For Google:

    1. Go to the Google Cloud Console.
    2. Create a new project.
    3. Go to "APIs & Services" > "Credentials".
    4. Click "Create Credentials" > "OAuth client ID".
    5. Select "Web application".
    6. Add http://localhost:3000 to "Authorized JavaScript origins".
    7. Add http://localhost:3000/api/auth/callback/google to "Authorized redirect URIs".
    8. Copy your Client ID and Client Secret.
  • For GitHub:

    1. Go to your GitHub settings > "Developer settings" > "OAuth Apps".
    2. Click "New OAuth App".
    3. Set the "Homepage URL" to http://localhost:3000.
    4. Set the "Authorization callback URL" to http://localhost:3000/api/auth/callback/github.
    5. Click "Register application".
    6. Generate a new client secret and copy both the Client ID and the new secret.

Now, add these credentials to your .env.local file. NextAuth.js v5 cleverly infers these variables based on the provider name.

ini
# .env.local
AUTH_SECRET="..."
AUTH_GOOGLE_ID="..."
AUTH_GOOGLE_SECRET="..."
AUTH_GITHUB_ID="..."
AUTH_GITHUB_SECRET="..."

Finally, update your auth.ts file to include the providers:

typescript
// auth.ts
import NextAuth from "next-auth"
import Google from "next-auth/providers/google"
import GitHub from "next-auth/providers/github"

export const { handlers, auth, signIn, signOut } = NextAuth({
  providers: [
    Google,
    GitHub,
  ],
})

And just like that, you've configured Google and GitHub authentication!

4. Protecting Routes, Server Components, and Server Actions

Now that we have a bouncer, we need to tell them which doors to guard. 🚪

The Problem: How do we restrict access to certain pages or features to only logged-in users?

The Solution: Use a combination of Next.js Middleware and the auth function provided by NextAuth.js.

Protecting Routes with Middleware

Middleware acts like a checkpoint for incoming requests. We can use it to redirect unauthenticated users away from protected pages.

Create a middleware.ts file in the root of your project (or at the same level as your app directory).

typescript
// middleware.ts
export { auth as middleware } from "@/auth"

By default, this will protect your entire application. To configure which routes are protected, you can export a config object:

typescript
// middleware.ts
import { auth } from "@/auth"

export default auth((req) => {
  // req.auth is available here
})

// Optionally, don't invoke Middleware on some paths
export const config = {
  matcher: ["/((?!api|_next/static|_next/image|favicon.ico).*)"],
}

The matcher allows you to specify which paths the middleware should run on. This example runs it on all paths except for a few common ones. You can customize this to only protect specific routes, like /dashboard.

Checking Sessions in Server Components

This is where the power of the App Router really shines. You can check the user's session directly within a Server Component.

typescript
// app/dashboard/page.tsx
import { auth } from "@/auth"
import { redirect } from "next/navigation"

export default async function DashboardPage() {
  const session = await auth()

  if (!session) {
    redirect("/api/auth/signin")
  }

  return (
    <div>
      <h1>Welcome to the Dashboard, {session.user?.name}!</h1>
      {/* Your protected content here */}
    </div>
  )
}

The auth() function will return the user's session if they are logged in, or null if they are not.

Securing Server Actions

Server Actions are functions that run on the server, often triggered by form submissions. It's crucial to ensure that only authenticated (and authorized) users can perform certain actions.

typescript
// app/actions.ts
'use server'

import { auth } from "@/auth"

export async function updateProfile(formData: FormData) {
  const session = await auth()

  if (!session?.user) {
    return { error: "You must be signed in to update your profile." }
  }

  // Logic to update the user's profile in the database
  // You can use session.user.id to identify the user

  return { success: "Profile updated successfully!" }
}

By checking the session at the beginning of your Server Action, you can prevent unauthorized users from making changes to your data.

And there you have it! A comprehensive, yet practical, guide to securing your Next.js application. You've learned how to choose an authentication strategy, set up the industry-standard NextAuth.js, implement social logins, and protect your application at every level. Your club is now secure, and your users can enjoy a safe and personalized experience. 🎉

Extra Reading & References

Challenge

You are building a Next.js application and need to implement authentication using NextAuth.js v5. Your task is to correctly configure NextAuth.js with both Google and GitHub providers and then set up middleware to protect the /dashboard route and all of its sub-paths.

Assume your environment variables (AUTH_SECRET, AUTH_GOOGLE_ID, AUTH_GOOGLE_SECRET, AUTH_GITHUB_ID, AUTH_GITHUB_SECRET) are already configured in a .env.local file.

You need to write the complete code for two separate files within the editor: auth.ts and middleware.ts.

auth.ts Requirements:

  1. Import NextAuth from next-auth.
  2. Import the Google and GitHub providers from their respective modules.
  3. Initialize NextAuth with a configuration object that includes a providers array containing both the Google and GitHub providers.
  4. Destructure and export the handlers, auth, signIn, and signOut functions from the result of the NextAuth call.

middleware.ts Requirements:

  1. Re-export the auth function from your local ./auth.ts module as the default middleware export.
  2. Define and export a config object.
  3. Inside the config object, add a matcher property. The value of this property should be an array containing a string pattern that applies the middleware to all routes that fall under /dashboard/.

Expected result

The provided code should contain the complete and correct implementations for both the auth.ts and middleware.ts files based on the requirements.

Correct auth.ts Implementation

This file should configure the NextAuth.js instance with the specified OAuth providers.

typescript
// Path: auth.ts
import NextAuth from "next-auth"
import Google from "next-auth/providers/google"
import GitHub from "next-auth/providers/github"

export const { handlers, auth, signIn, signOut } = NextAuth({
  providers: [Google, GitHub],
})

Correct middleware.ts Implementation

This file should export the authentication middleware and a config object to specify the protected routes.

typescript
// Path: middleware.ts
export { auth as middleware } from "./auth"

export const config = {
  matcher: ["/dashboard/:path*"],
}
typescript

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.