awinogrodzki/next-firebase-auth-edge

Making "/" public causes TOO_MANY_REDIRECTS

fedetoledo opened this issue · 1 comments

My app only have a few private routes. Is there a way to make "/" public?

If I add it to PUBLIC_PATHS and try to enter a private path, i am redirected to /login?redirectTo=/{privatePath} and after logging in it just breaks with TOO_MANY_REDIRECTS error

Okay I think the following works:
I set a new variable AUTH_PATHS and only use it for valid tokens, so if the user is logged in and the path is "/", instead of looking in PUBLIC_PATHS to redirect, it will look into AUTH_PATHS which will be false, and then the middleware will keep running normally.

const PUBLIC_PATHS = [
  '/register',
  '/login',
  '/reset-password',
  '/',
];

const AUTH_PATHS = ['/login', '/reset-password'];

export async function middleware(request: NextRequest) {
  return authMiddleware(request, {
    loginPath: '/api/login',
    logoutPath: '/api/logout',
    refreshTokenPath: '/api/refresh-token',
    enableMultipleCookies: authConfig.enableMultipleCookies,
    apiKey: authConfig.apiKey,
    cookieName: authConfig.cookieName,
    cookieSerializeOptions: authConfig.cookieSerializeOptions,
    cookieSignatureKeys: authConfig.cookieSignatureKeys,
    serviceAccount: authConfig.serviceAccount,
    handleValidToken: async ({ token, decodedToken, customToken }, headers) => {
      console.log('isValid');
      // Authenticated user should not be able to access /login, /register and /reset-password routes
      if (AUTH_PATHS.includes(request.nextUrl.pathname)) {
        return redirectToHome(request);
      }

      return NextResponse.next({
        request: {
          headers,
        },
      });
    },
    handleInvalidToken: async (_reason) => {
      return redirectToLogin(request, {
        path: '/login',
        publicPaths: PUBLIC_PATHS,
      });
    },
    handleError: async (error) => {
      console.error('Unhandled authentication error', { error });

      return redirectToLogin(request, {
        path: '/login',
        publicPaths: PUBLIC_PATHS,
      });
    },
  });
}

Hopefully this can help anyone that finds the same problem.