grayson
grayson

Reputation: 1037

Next.js custom url name (url re-writing)

I have a project in Next.js where I have 2 different users: admin and employee.

I have set up 2 folders inside pages; /admin and /users. Each folder/users has its own subpages. for example /admin/dashboard and /employee/dashboard etc

I am trying to obfuscate the role, so that instead of displaying the url: "/admin/dashboard", if the user is an admin, I would like the url to display "/dashboard" which actually gets the "admin/dashboard" page.

I have tried next.js.config and that works perfectly when I do a full page refresh on /dashboard

module.exports = {
    async rewrites() {
        return [
        {
          source: '/:path*',
          destination: '/admin/:path*',
        },
      ]
    },
  }

However, if I set my link to "/dashboard", it does not work. I have tried middleware, and I can get "/" to redirect to "/admin", but I want the opposite. ie if I go to "/" it will use the "/admin/" page, but cannot work out how to achieve my goal (if it is possible !)

if (request.nextUrl.pathname.startsWith('/dashboard')) {

    url.pathname = "/admin/dashboard";
    return NextResponse.redirect(url);
}

Any help greatly appreciated

Upvotes: 0

Views: 1232

Answers (1)

koolskateguy89
koolskateguy89

Reputation: 413

You can use as from router.push and the Link component.

For example:

import Link from 'next/link';
import { useRouter } from 'next/router';

export default function Example() {
  const router = useRouter();

  const handleEmployeeClick = () => {
    // will show page from /employee/dashboard but show as /dashboard
    router.push('/employee/dashboard', '/dashboard');
  };

  return (
    <>
      <button onClick={handleEmployeeClick}>
        Go to dashboard (employee only)
      </button>

      <Link href="/admin/dashboard" as="/dashboard">
        Go to dashboard (admin only)
      </Link>
    </>
  );
}

Upvotes: 1

Related Questions