The project i work in uses builder io with next.js.
And we want to be able to create a protected route.
So i was wondering is it possible to get all the users and their roles so that the route can be accessible accordingly on any environment.
So basically i want to be able to get the users from here → Builder.io: Visual Development Platform and based on given roles to make some routes accessible while others not in the next js app via middleware.
Hey @Mehan , Currently, Builder.io does not directly provide an API endpoint to fetch a list of users and their roles. User and role management is primarily handled within the Builder.io interface and settings.
If you need to implement protected routes based on user roles while using Builder.io for content, you’ll need to integrate a custom user management system and use Builder.io’s custom roles for content management.
Suggested Approach for Protected Routes in Next.js:
1. User Management System: Set up user authentication and role management using a system like Firebase or Auth0.
2. Middleware for Protected Routes in Next.js: Create a middleware that verifies user roles before granting access to certain routes.
// middleware.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
// Mock function to get user roles, replace this with your own user management logic
async function getUserRoles(userToken: string): Promise<string[]> {
// Replace this with logic to fetch user roles from your user management system
return [];
}
export async function middleware(request: NextRequest) {
const userToken = request.cookies.get('token');
if (!userToken) {
return NextResponse.redirect(new URL('/login', request.url));
}
const userRoles = await getUserRoles(userToken);
const url = request.nextUrl.clone();
url.pathname = '/403';
// Example protected route (/admin) check
if (request.nextUrl.pathname.startsWith('/admin') && !userRoles.includes('admin')) {
return NextResponse.redirect(url);
}
// Continue to the requested route if access is allowed
return NextResponse.next();
}
// Apply the middleware to all routes
export const config = {
matcher: '/admin/:path*', // Adjust to match the routes you want to protect
};
By following this approach, you can create protected routes in your Next.js application based on user roles, while leveraging Builder.io for content management and creation. Communication between your user management system and the Builder.io content model allows you to enforce role-based access control effectively.