Next.js Discord

Discord Forum

How to check path in middleware?

Unanswered
Atlantic mackerel posted this in #help-forum
Open in Discord
Atlantic mackerelOP
Hey guys, I'm creating dynamic routes and I wonder what if the path is not id pattern? My id is from Mongodb actually, so User'd get this link

http://localhost:3000/6606b05eb0b1fc18a88701e2


and also I wanna the other path like

http://localhost:3000/administrator
http://localhost:3000/home
http://localhost:3000/login
http://localhost:3000/register


how can I detect if the path pattern not correct with that id?

10 Replies

@Atlantic mackerel you can make it so check if the nextUrl.pathname starts with a number or not, and accordingly have your logic
or keep an array of pages which are site pages like /dashboard and check if nextUrl.pathname includes in the array
@Arinji <@273686048121290763> you can make it so check if the nextUrl.pathname starts with a number or not, and accordingly have your logic
Atlantic mackerelOP
oh, like this?

import {NextResponse} from 'next/server'
import type {NextRequest} from 'next/server'

export function middleware(request: NextRequest) {
    let cookie = request.cookies.get('nextjs')
    if (request.url.startsWith("/dashboard")) {
        return NextResponse.redirect(new URL('/', request.url))
    }
}

export const config = {
    matcher: '/:path*',
}
can you log request.url once
you probs need to do url.pathname since url will be the entire thing including http://localhost:3000
Atlantic mackerelOP
but I wonder i changed this way, can I use client cookie still
I did before like this
export default function Home() {
    let {userUuid} = useAccount()
    const router = useRouter()

    useEffect(() => {
        if (userUuid !== undefined) {
            router.push(`/${userUuid}`)
        }

    }, []);
    return (
        <main className="">

        </main>
    );
}



inner that useAccount function contains this

import {getCookie, hasCookie, setCookie} from "cookies-next";
const [userUuid, setUserUuid] = useState<string>(getCookie("user") as string);
export function middleware(request: NextRequest) {
    let cookie = request.cookies.get('nextjs')
    if (request.url.startsWith("http://localhost:3000/dashboard")) {
        return NextResponse.redirect(new URL('http://localhost:3000/', request.url))
    }
}
like this?