# How can I implement user authentication and manage user sessions for a website using Builder.io as the backend and Next.js as the frontend? Looking for documentation or examples for this integration.

**URL:** <https://forum.builder.io/t/how-can-i-implement-user-authentication-and-manage-user-sessions-for-a-website-using-builder-io-as-the-backend-and-next-js-as-the-frontend-looking-for-documentation-or-examples-for-this-integration/15902>\
**Category:** Technical Questions\
**Tags:** nextjs\
**Created:** [October 27, 2025, 9:28am UTC](https://forum.builder.io/t/how-can-i-implement-user-authentication-and-manage-user-sessions-for-a-website-using-builder-io-as-the-backend-and-next-js-as-the-frontend-looking-for-documentation-or-examples-for-this-integration/15902 "2025-10-27T09:28:08Z")\
**Posts on this page:** 1\
**Showing post:** 2

<div class="post-metadata">

**Author:** ![manish-sharma](https://avatars.discourse-cdn.com/v4/letter/m/8797f3/32.png) [@manish-sharma](https://forum.builder.io/u/manish-sharma)\
**Post date:** [October 27, 2025, 11:11am UTC](https://forum.builder.io/t/how-can-i-implement-user-authentication-and-manage-user-sessions-for-a-website-using-builder-io-as-the-backend-and-next-js-as-the-frontend-looking-for-documentation-or-examples-for-this-integration/15902/2 "2025-10-27T11:11:40Z")

</div>

Hello @Srivathsa1503,

You want to add: a user authentication layer + session management (login/logout, protected routes/pages, user data persistence)

- [Builder.io](http://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:

**[Builder.io](http://Builder.io) + Next.js integration**

- There is official documentation on how to [integrate Builder](https://www.builder.io/c/docs/integrating-builder-pages) in a Next.js app.

- For example, you initialise Builder in your app:

- 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:

- You’ll need to manage:

- Example: On the Builder forum someone asked about Auth0 + Next.js + [Builder.io](http://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](http://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`/`getInitialProps` to check session.

#### Step 2: Determine which pages/content are public vs private

- Public content: pages built via [Builder.io](http://Builder.io) that anyone (unauthenticated) can view

- Private content: pages/components that require login

#### 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:

- On the page or component side you can check `session` and 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:

- 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](http://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](http://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 `/_builder` or `/api/builder` preview 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.tsx` server 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](http://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)

```ts
// 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:

1. **Auth / Session** — define how users log in, how sessions are stored, how you identify logged-in users.
2. **[Builder.io](http://Builder.io) Content Fetching** — use the Builder SDK to fetch content, pass user attributes if needed, render via Next.js.
3. **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:

> **[Integrate Pages](https://www.builder.io/c/docs/integrating-builder-pages)**
>
> Builder is an AI-Powered Visual Development Platform that helps teams generate, iterate, and optimize web and mobile experiences in seconds instead of sprints.

> **[Setting up visual drag-and-drop page building with Next.js](https://www.builder.io/blog/visual-next-js)**
>
> Learn how to create pages and sections in Next.js. Hand off a toolkit to your non-developers to create and optimize pages within your guidelines.

> [@Securing pages with Auth0/Next.js](https://forum.builder.io/t/securing-pages-with-auth0-next-js/802):
>
> Hi all, I think a working solution to this would be very valuable to anyone seeking to create a portal leveraging a dedicated identity solution like Auth0. Has anyone had success using Auth0 with [Builder.io](http://Builder.io) using a next.js? What I would like to achieve is: allow public access to common areas of the site - i.e. homepage, about, etc. secure member-only pages using Auth0 allow non-technical users (site admins) to update content using the builder editor some links that I’ve used to get a pure n…

[https://medium.com/%40neerajvageele451/integrate-builder-io-in-your-next-js-web-app-9e7181837cb](https://medium.com/%40neerajvageele451/integrate-builder-io-in-your-next-js-web-app-9e7181837cb)

> [@Issues with Accessing Dynamic Routes with Clerk Authentication and Builder.io](https://forum.builder.io/t/issues-with-accessing-dynamic-routes-with-clerk-authentication-and-builder-io/6088):
>
> What are you trying to accomplish I’m encountering an issue with accessing dynamic routes in my Next.js application that uses Clerk for authentication, and the routes are managed by [Builder.io](http://Builder.io). Specifically, I’m getting a 401 Unauthorized response when trying to access dynamic routes such as /studio/variis. I need to ensure that these dynamic routes are correctly recognized as public or private by Clerk middleware and can be accessed without authentication issues. Code stack you are integratin…

> [@Get all users from builder io space in next.js app?](https://forum.builder.io/t/get-all-users-from-builder-io-space-in-next-js-app/6458):
>
> Hello, i have a question. 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](https://builder.io/account/users) and based on given roles to make some routes accessible while others not in the next js app via middleware. Is there api endpo…

---

_[View the full topic](https://forum.builder.io/t/how-can-i-implement-user-authentication-and-manage-user-sessions-for-a-website-using-builder-io-as-the-backend-and-next-js-as-the-frontend-looking-for-documentation-or-examples-for-this-integration/15902)._
