Hello @Srivathsa1503,
You want to add: a user authentication layer + session management (login/logout, protected routes/pages, user data persistence)
-
Builder.io handles content/pages/components (editable by non-devs)
-
Auth/user sessions are handled by your app’s own auth layer (NextAuth, Auth0, Clerk, etc) or custom backend
-
Your Next.js app then has to integrate both:
- Render Builder content for public pages
- Use session/user state for protected pages/routes
Builder.io + Next.js integration
-
There is official documentation on how to integrate Builder in a Next.js app.
-
For example, you initialise Builder in your app:
import { builder, BuilderComponent } from '@builder.io/react'; builder.init(YOUR_PUBLIC_API_KEY);Then fetch builder content (e.g., in
getStaticPropsorgetServerSidePropsor with the App Router) and render via<BuilderComponent model="page" content={page} />. -
Thus the content portion is clear; the missing piece is how you layer auth + session on top.
Auth & session management
-
Since you’re using Next.js, you have multiple options:
- Use a library such as NextAuth.js (widely used)
- Use a service like Auth0, Clerk, etc
- Build your own sessions (JWT or cookie based) via Next.js API routes or middleware
-
You’ll need to manage:
- Login and create session / issue cookie or token
- Protect routes/pages – for example only allow authenticated users to view certain pages/components
- Handle logout / session expiry
- Persist user info (profile, roles) in your own backend or database
-
Example: On the Builder forum someone asked about Auth0 + Next.js + Builder.io for member-only pages. The answer: yes you can, by gating content in your app (Builder isn’t doing the auth itself). ([Builder.io Forum])
Here’s a suggested implementation path:
Step 1: Set up authentication & session
- Choose your auth solution (e.g., NextAuth.js)
- Configure provider(s) (email/password, OAuth, etc)
- Set up session cookies (secure, httpOnly) or JWTs
- Provide a user context in your app (e.g., via React Context, or via
useSession()hook) - Protect pages via middleware or
getServerSideProps/getInitialPropsto check session.
Step 2: Determine which pages/content are public vs private
-
Public content: pages built via Builder.io that anyone (unauthenticated) can view
-
Private content: pages/components that require login
- Either you build the page in Next.js and fetch Builder content conditionally
- Or you treat private section separately (e.g., builder content + wrapper that checks session).
Step 3: Implement route protection in Next.js
-
With the App Router you can use middleware (
middleware.ts) to check requests for certain routes. -
Example:
export async function middleware(req) { const session = await getSessionFromCookieOrToken(req); if (!session && req.nextUrl.pathname.startsWith('/members')) { return NextResponse.redirect('/login?callbackUrl=' + req.url); } return NextResponse.next(); } export const config = { matcher: ['/members/:path*'] // adjust to your protected routes }; -
On the page or component side you can check
sessionand if not present, redirect client-side or show login.
Step 4: Fetching Builder content with user context
-
For pages that might behave differently for authenticated vs non-authenticated users (for example personalised content), you can pass user attributes when fetching from Builder. For example:
const page = await builder.get('page', { userAttributes: { urlPath: somePath, loggedIn: Boolean(session), userId: session?.user.id, // any custom attribute } }).toPromise();→ I found in the medium article they pass
userAttributes. ([Medium][4]) -
This allows you to make Builder content conditional (via Builder targeting rules) based on user state (logged in/out, segments, etc).
-
Note: If the content is strictly private you might instead skip Builder’s preview for unauthenticated users and serve your custom page.
Step 5: Preview / Editor mode considerations
- Since you’re using Builder.io, you probably want preview mode (builders can preview changes before publish).
- Builder’s preview mode sets special cookies/URL params to allow the editor to fetch unpublished content. Make sure your auth/session system doesn’t interfere with those.
- Example: On the forum there was a report of issues with dynamic routes + auth middleware using Clerk + Builder. ([Builder.io Forum][5])
- Make sure your middleware allows the Builder editor (or preview URLs) to pass through (i.e., treat them as public routes). Example: In your matcher you might exclude
/_builderor/api/builderpreview endpoints.
Step 6: Deployment / hosting (you use AWS)
- Make sure environment variables for your auth solution are correctly configured (e.g., secret keys, cookie domain).
- Ensure your Next.js app (App Router) uses correct configuration for cookies + domain + secure flag.
- If you fetch content from Builder server-side (getServerSideProps or the new App Router’s
page.tsxserver component) ensure sessions/cookies are passed in requests. - If using Serverless or Edge functions, be mindful of cookie reading/writing.
Specific considerations for your scenario
- You are using the App Router (Next.js) rather than Pages Router, so your route protection logic will need to align with that (middleware + layout handling).
- Your hosting is AWS (not Vercel) — ensure any builder preview URLs (which sometimes use Vercel preview tokens) are supported (you may need special headers/cookies).
- You previously encountered login issues within the Builder editor due to session cookie handling — you’ll want to ensure your auth logic does not block the Builder editor iframe, preview endpoints, or builder API calls. Mark those routes as public in your middleware.
- If you also have user roles (support vs engineering vs admin) you’ll need to store those in your user store and use them to gate access to certain builder content or pages (Builder does not expose an API to list users/roles for your site directly). ([Builder.io Forum][7])
- When you fetch builder content based on user context, remember to pass any user identifier server-side to avoid leaking private data to unauthenticated users.
Proposed Code Skeleton (pseudo)
// middleware.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import { getSessionFromReq } from './lib/auth';
export async function middleware(req: NextRequest) {
const { pathname } = req.nextUrl;
const session = await getSessionFromReq(req);
// allow builder preview/editor routes
if (pathname.startsWith('/_builder') || pathname.startsWith('/api/builder')) {
return NextResponse.next();
}
// protect member routes
if (pathname.startsWith('/members') && !session) {
const url = req.nextUrl.clone();
url.pathname = '/login';
url.searchParams.set('callbackUrl', req.url);
return NextResponse.redirect(url);
}
return NextResponse.next();
}
export const config = {
matcher: ['/members/:path*']
};
// In a page component (App Router server component)
import { builder, BuilderComponent } from '@builder.io/react';
import { getServerSession } from './lib/auth';
const apiKey = process.env.BUILDER_API_KEY!;
builder.init(apiKey);
export default async function Page({ params }) {
const session = await getServerSession(); // your session logic
const urlPath = '/' + (params.slug?.join('/') || '');
const page = await builder.get('page', {
userAttributes: {
urlPath,
loggedIn: Boolean(session),
userId: session?.user.id
}
}).toPromise();
if (!page) {
// handle 404
}
return (
<BuilderComponent model="page" content={page} />
);
}
In short, your integration will involve three layers:
- Auth / Session — define how users log in, how sessions are stored, how you identify logged-in users.
- Builder.io Content Fetching — use the Builder SDK to fetch content, pass user attributes if needed, render via Next.js.
- Route Protection & Access Control — via Next.js middleware or server logic ensure only authenticated users access member routes, and ensure the Builder preview/editor routes are not blocked.
Here are useful links: