Next.js Discord

Discord Forum

Authentication logic in middleware

Unanswered
Purple Martin posted this in #help-forum
Open in Discord
Purple MartinOP
I'm setting up cookie based authentication in a next.js 13 app.

So far, everything works fine except the logout action.

I'd like to have these 4 features:
- When my user signs in, he's redirected to "/"
- When he signs out, he's redirected to "/login"
- He can access public pages, regardless of cookie presence
- If he tries to access a protected page without being signed in, he's redirected to "/login"


So I came up with this middleware:

import { NextRequest, NextResponse } from "next/server";

import { HOME_PATH, LOGIN_PATH, TERMS_PATH } from "constants/paths";

const accessTokenCookieName =
  process.env.ACCESS_TOKEN_COOKIE_NAME ?? "hal.access-token";
const PUBLIC_PATHS = [LOGIN_PATH, TERMS_PATH];

/**
 * Redirect to login page if no access token is found
 */
export function middleware(request: NextRequest) {
  const token = request.cookies.get(accessTokenCookieName);

  if (token) {
    // redirect to homepage if token is found on login page
    if (request.nextUrl.pathname === LOGIN_PATH) {
      return NextResponse.redirect(new URL(HOME_PATH, request.nextUrl.origin));
    }

    return NextResponse.next();
  }

  // Skip middleware for the public pages
  if (PUBLIC_PATHS.includes(request.nextUrl.pathname)) {
    return NextResponse.next();
  }

  return NextResponse.redirect(new URL(LOGIN_PATH, request.nextUrl.origin));
}

export const config = {
  /**
   * Match all request paths except:
   * - API
   * - NextJS chunks
   * - favicon.ico
   */
  matcher: ["/((?!api|_next/static|_next/image|favicon.ico).*)"],
};

// server action file
export async function logout() {
  cookies().delete(getAccessTokenCookieName());
  // Redirect to login page
  redirect(LOGIN_PATH);
}


Everything works fine, except the 2nd feature: when I click on my Logout button:
- The cookie is removed
- the URL is updated (goes from "/" to "/login")
- the dom does not refresh

Did I miss something ? I thought that using redirect would handle the client side effect

0 Replies