In the middleware file, I want to check if the user is authenticated and allowed to visit specific pages.
Currently how I do it is as following:
// Some pageconst Page = () => { ... }Page.auth = { route: "/page" protectFromNonAuth: { roles: ["ADMIN"] }}// NextJS Middleware fileconst routes = [ { route: "/page" protectFromNonAuth: { roles: ["ADMIN"] } }]export const middleware = async (req: NextRequest) => { // Get the current route and find it in the routes array and check if user has // permission to visit the page.}
// Some pageconst Page = () => { ... }Page.auth = { route: "/page" protectFromNonAuth: { roles: ["ADMIN"] }}// NextJS Middleware fileconst routes = [ { route: "/page" protectFromNonAuth: { roles: ["ADMIN"] } }]export const middleware = async (req: NextRequest) => { // Get the current route and find it in the routes array and check if user has // permission to visit the page.}
This works but what I don't like about it is that I now have double code for the same thing.
When I import the auth functionality from all the pages, so like
const routes = [ Page.auth, OtherPage.auth];
const routes = [ Page.auth, OtherPage.auth];
it works in dev mode but when building for production, it says
Dynamic Code Evaluation (e. g. 'eval', 'new Function', 'WebAssembly.compile') not allowed in Edge Runtime
Dynamic Code Evaluation (e. g. 'eval', 'new Function', 'WebAssembly.compile') not allowed in Edge Runtime
because I import those auth from the pages.
Does someone know a better and cleaner way of doing this? I have quite some pages and I don't want to forgot also adding the auth in the routes array in the middleware.