Next.js Discord

Discord Forum

middleware routes control issue

Unanswered
Graham posted this in #help-forum
Open in Discord
i'm using next 15
so i have a [username] folder in my app folder i use it to show profiles publicly without logging in
the issue is the access will be something like mysite.com/username
so i show everything... even protected pages like /dashboard .. /api and more stuff
i can't find a solution for this..... i already have a middleware that is protecting these pages
import NextAuth from "next-auth";
import authConfig from "@/auth.config";
import {DEFAULT_LOGIN_REDIRECT, apiAuthPrefix, authRoutes, publicRoutes} from "@/routes"
const {auth} = NextAuth(authConfig)

export default auth((req)=>{
    const {nextUrl} = req;
    const isLoggedIn = !!req.auth;
    const isApiRoute = nextUrl.pathname.startsWith(apiAuthPrefix);
    const isPublicUrl = publicRoutes.includes(nextUrl.pathname)
    const isAuthUrl = authRoutes.includes(nextUrl.pathname)

    /*/ routes checking  /*/

    if(isApiRoute){ return}
    if(isAuthUrl){
        if(isLoggedIn){
            return Response.redirect(new URL(DEFAULT_LOGIN_REDIRECT, nextUrl));
        }
        return;
    }
    if(!isLoggedIn && !isPublicUrl){
        return Response.redirect(new URL("/", nextUrl));
    }

    return;
})
export const config = {
    matcher: [
      "/((?!api|_next/static|_next/image|favicon.ico|.*\\..*).*)"
    ]
  };
  

2 Replies

import NextAuth from "next-auth";
import authConfig from "@/auth.config";
import { DEFAULT_LOGIN_REDIRECT, apiAuthPrefix, authRoutes, publicRoutes } from "@/routes";

const { auth } = NextAuth(authConfig);

export default auth((req) => {
  const { nextUrl } = req;
  const isLoggedIn = !!req.auth;
  const isApiRoute = nextUrl.pathname.startsWith(apiAuthPrefix);
  const isPublicUrl =
    publicRoutes.includes(nextUrl.pathname) ||
    /^\/[^\/]+$/.test(nextUrl.pathname); // this here checks if there is more than one path... so something like /example/something

  const isAuthUrl = authRoutes.includes(nextUrl.pathname);

  if (isApiRoute) return;

  if (isAuthUrl) {
    if (isLoggedIn) {
      return Response.redirect(new URL(DEFAULT_LOGIN_REDIRECT, nextUrl));
    }
    return;
  }

  if (!isLoggedIn && !isPublicUrl) {
    return Response.redirect(new URL("/", nextUrl));
  }

  return;
});

export const config = {
  matcher: [
    "/((?!api|_next/static|_next/image|favicon.ico|.*\\..*).*)"
  ]
};

is it safe to use this middleware instead????
it allows entrance for /example
but not /example/something
and i have to handle non-logged in users manually in my
/dashboard, /admin, /page...... etc