0

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

1 Answer 1

1

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>
    </>
  );
}
Sign up to request clarification or add additional context in comments.

2 Comments

this has solved half of my issue. Thank you. However, a user can still manually enter /employee/dashboard and the url with show that rather then just /dashboard
@grayson Then you would have to add role-based authentication in /employee/dashboard and admin/dashboard to stop users from accessing the specific page. If you want them to be able to just enter /dashboard, you can create a /dashboard page and automatically redirect to the correct dashboard page depending on the user's role.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.