Build a multi-layout system in Next.js using parallel routes and intercepting routes to create a modal that opens on top of the current page when clicked but acts as a standalone page if the URL is opened directly.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Explaining Next.js Modal with Parallel and Intercepting Routes
This approach uses Next.js app router’s parallel routes and intercepting routes to render a modal overlay for /photo/[id] when navigated from /feed, but shows the photo page standalone if accessed directly via URL. The root layout defines a modal parallel slot with a default empty component. The intercept route in app/feed/@modal/(..)photo/[id] catches /photo/[id] navigation from /feed and renders the modal overlay while keeping /feed visible in the main content. Direct access to /photo/[id] loads the standalone page with no modal.
The file structure and key code illustrate this pattern clearly. The modal route is a client component to handle closing via router.back(). This setup preserves the background page during in-app navigation and shows a full page on direct visits.
With the App Router you can keep the “background” route mounted and render another route into a separate slot. If that slot has a default that returns null, the same URL will fall back to a normal full–page render when it isn’t being intercepted.
The pattern looks like this:
code
app/
├─ layout.tsx // root layout renders the main content + modal slot
├─ @modal/
│ └─ default.tsx // default content for the modal slot (renders nothing)
├─ feed/
│ ├─ page.tsx // your feed page
│ └─ @modal/
│ └─ (..)photo/
│ └─ [id]/
│ └─ page.tsx // intercepted photo route, rendered as a modal
└─ photo/
└─ [id]/
└─ page.tsx // standalone photo page
Root layout with a modal parallel route slot:
tsx
// app/layout.tsx
import './globals.css';
export default function RootLayout({
children,
modal, // comes from the @modal parallel route
}: {
children: React.ReactNode;
modal: React.ReactNode;
}) {
return (
<html lang="en">
<body>
<div className="app-shell">{children}</div>
{modal}
</body>
</html>
);
}
Default content for the modal slot (so it’s optional):
tsx
// app/@modal/default.tsx
export default function ModalDefault() {
return null;
}
Navigating from /feed to /photo/:id via a <Link> is intercepted by app/feed/@modal/(..)photo/[id]/page.tsx because of the ( .. ) segment, and its content is rendered into the modal slot. The children slot remains the feed, so the photo appears on top of it as a modal.
If you hit /photo/:id directly (or from a route that doesn’t define an intercept), the normal app/photo/[id]/page.tsx is rendered as a standalone page. The @modal slot renders default.tsx, which is null.