Creating the Sign Out Flow

Course: Next.js Authentication and Authorization

Introduction

Now that we've implemented the sign up and sign in logic, all that's left to do is implement the log out functionality. Compared to the previous two functions, building the log out functionality is much simpler. At this point, the code we implement should look very familiar to you.

Building the Sign Out API Route

AT this point, you should be rather familiar with creating API routes. So I'll simply share the code for the route.ts file for the log out API route:

import { NextResponse } from "next/server"
import { signOut } from "@/lib/auth"

export async function POST() {
  try {
    await signOut()
    return NextResponse.json({ success: true })
  } catch (error) {
    console.error("Logout error:", error)
    return NextResponse.json(
      { error: "Internal server error" },
      { status: 500 }
    )
  }
}

This is super straightforward. We simply call the signOut function which we will define later, and return a response to the front end.

Building the Sign Out Logic

Back in the auth.ts file, we'll create the signOut function:

export async function signOut() {
  const session = await getSession()
  session.destroy()
}

As you can see, it's super simple. We just get the session and call session.destroy() to remove the cookie.

And just like that, we've created the core functionality of the authentication flow. The next step is to implement authorization and role based access to control who can view what pages.

Building the Sign Out Button

Since logging out requires a user interaction (clicking a button), our logout button has to be a client component. This reusable component will help keep the code clean and avoids repeating the same fetch logic across multiple pages. Furthermore, most of our app will be built on server components, which are faster and render on the server. So we'll need to keep this Sign Out button in its own client component.

"use client"
import { useRouter } from "next/navigation"
import React from "react"

const SignOutButton = () => {
  const router = useRouter()
  const handleSignOut = async () => {
    try {
      await fetch("/api/auth/logout", { method: "POST" })
      router.push("/signin")
      router.refresh()
    } catch (error) {
      console.error("Logout failed:", error)
    }
  }
  return (
    <button
      onClick={handleSignOut}
      className="bg-red-600 hover:bg-red-700 text-white px-4 py-2 rounded-md text-sm font-medium"
    >
      Sign Out
    </button>
  )
}

export default SignOutButton