Next.js Discord

Discord Forum

Using middleware for urls

Unanswered
Villano de Las Encartaciones posted this in #help-forum
Open in Discord
Villano de Las EncartacionesOP
I am currently trying to allow admin user to have access to a url for example /dashboard

If the url is entered in the browser the content should only display for admin

1 Reply

Sun bear
You can follow the docs:

import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
 
export function middleware(request: NextRequest) {
  if (request.nextUrl.pathname.startsWith('/about')) {
    return NextResponse.rewrite(new URL('/about-2', request.url))
  }
 
  if (request.nextUrl.pathname.startsWith('/dashboard')) {
    return NextResponse.rewrite(new URL('/dashboard/user', request.url))
  }
}


https://nextjs.org/docs/app/building-your-application/routing/middleware

You can also work with matcher.

Do something like:

const user = getUser();
if (!user) {
// url based checks
}