Ecopages0.10.3

Creating Layouts in Ecopages

Layouts wrap page content with shared chrome — navigation, sidebars, providers, and other structure that repeats across routes. This guide covers document includes, declared layout components, single and nested layout stacks, and how layouts interact with SPA routing.

Includes Files

Includes files define the outer document shell. They live under src/includes (for example html.tsx and head.tsx with Ecopages JSX), and every Page except an HTML Page needs the html template there. HTML Pages are the exception: they use a built-in HTML template when no src/includes/html.* exists. They cannot declare a layout, so use an eco.page() Page for a route that needs one.

html.tsx

Defines the overall HTML envelope:

import { eco } from '@ecopages/core';
import type { JsxRenderable } from '@ecopages/jsx';

export const Html = eco.html<JsxRenderable>({
	dependencies: {
		stylesheets: ['./html.css'],
	},
	render: ({ children }) => <html lang="en">{children}</html>,
});

head.tsx

Defines <head> content — title, meta, icons:

import { eco, type PageHeadProps } from '@ecopages/core';
import type { JsxRenderable } from '@ecopages/jsx';

export const Head = eco.component({
	render: ({ metadata, children }: PageHeadProps<JsxRenderable>) => (
	<head>
		<meta charset="UTF-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1.0" />
		<title>{metadata.title}</title>
		<meta name="description" content={metadata.description} />
		<link rel="icon" href="/favicon.ico" />
		{children}
	</head>
	),
});

Includes are applied automatically. Pages and route layouts render inside this shell — they do not replace it.

Layout components

A layout is a plain function typed with LayoutProps, or an eco.layout() result when it needs a wrapper. LayoutProps makes children required, so eco.page({ layout }) rejects a component that does not take children. A layout imports its own CSS and components like any plain function: discovery delivers them with the page, and they stay with the layout across client-side navigation.

import type { LayoutProps } from '@ecopages/core';
import type { ReactNode } from 'react';
import './base-layout.css';

export function BaseLayout({ children }: LayoutProps<ReactNode>) {
	return <main>{children}</main>;
}

Use eco.layout() when the layout declares browser scripts, modules, stylesheet attributes, or an integration override. Reserve eco.html() for the document shell in src/includes.

A layout must render children. TypeScript accepts a function that ignores them, so composition checks it: when a layout renders without its page, ecopages build fails with Layout <name> (<file>) did not render its children, a development request logs it as a warning, and a production request returns the layout's HTML unchanged, so a layout that shows a sign-in gate instead of the page still works on a dynamic route. An eco.layout() result is named after its file; a plain function is named by its function name, with the file of the page that uses it.

Single layout on a page

Assign the layout on eco.page(). EcoPages wraps render output automatically — do not manually nest the layout inside render unless you have an exceptional one-off case.

import { eco } from '@ecopages/core';
import { BaseLayout } from '@/layouts/base-layout';

export default eco.page({
	layout: BaseLayout,
	metadata: () => ({
		title: 'Home',
		description: 'Welcome',
	}),
	render: () => (
		<>
			<h1>Welcome to Ecopages</h1>
			<p>This is the homepage.</p>
		</>
	),
});

Nested layouts (outer → inner)

Pages can declare multiple layout tiers. Pass an array in outer → inner order:

import { eco } from '@ecopages/core';
import { AppShell } from '@/layouts/app-shell';
import { DocsSection } from '@/layouts/docs-section';

export default eco.page({
	layout: [AppShell, DocsSection],
	render: () => <h1>Documentation</h1>,
});

EcoPages normalizes the stack to:

  • config.layouts — component references per tier
  • config.layoutEntries — components plus optional per-tier props factories

Per-tier layout props

When a tier needs route or request data, use a layout entry object. Its props factory returns the props of that layout:

layout: [
	AppShell,
	{
		component: DocsSection,
		props: ({ params }) => ({ activeSlug: params?.slug }),
	},
],

A layout receives request data only through this factory: the component gets what the factory returns and no locals prop. The factory runs on the server, and its result is also sent to the browser for hydration, so return only what the browser may see, such as the user and not the whole session.

What the factory receives follows the Page's cache strategy:

  • On a cache: 'dynamic' Page it receives params, query and locals. Written inline, locals is typed from the Page's middleware list, like the Page's props hook.
  • On a static or revalidating Page it receives params and query. There is no request, so reading locals is a type error.
export default eco.page({
	cache: 'dynamic',
	middleware: [authMiddleware],
	layout: [AppShell, { component: DocsSection, props: ({ locals }) => ({ viewer: locals.session.user.email }) }],
	render: () => <h1>Documentation</h1>,
});

A layout entry shared by many Pages annotates the locals it reads once, on the factory parameter, such as ({ locals }: { locals: { session: Session } }). A Page whose middleware does not provide them, or a static Page, is a compile error.

The factory never runs in the browser: the browser build removes the factory of an entry written inline in eco.page(), together with the .server imports only it uses. A shared entry imported from another module keeps its factory in the browser bundle, so the browser build fails if that factory imports a .server module. See Request Locals for how request data reaches layout tiers during SSR and hydration.

Shared outer layouts and SPA navigation

On React sites with @ecopages/react-router, persistLayouts is enabled by default. A layout module has one URL, so every page that imports a layout gets the same function, and React keeps a tier mounted while consecutive pages pass the same function at the same position. Two routes such as [AppShell, Docs] and [AppShell, Settings] share one mounted AppShell during client navigation; only the inner tier swaps. React state in the outer layout survives SPA transitions.

When a Layout and multiple Pages need one module instance for shared state (for example, a query client or MobX store), Ecopages already loads that package once for every Page and Layout. See Shared browser modules in the React integration guide.

Note: Editing a layout in development reloads its module, so the new function replaces the mounted tier and its state resets.

Layout dependencies

A layout's local CSS and component imports are discovered. Declare browser scripts on eco.layout():

import { SiteHeader } from '@/components/site-header';
import { eco, type LayoutProps } from '@ecopages/core';
import type { JsxRenderable } from '@ecopages/jsx';
import './base-layout.css';

export const BaseLayout = eco.layout({
	dependencies: {
		scripts: ['./base-layout.script.ts'],
	},
	render: ({ children }: LayoutProps<JsxRenderable>) => (
		<>
			<SiteHeader />
			<main>{children}</main>
		</>
	),
});

Bare side-effect imports in a layout or its scripts follow the browser module rules.

Every entry in dependencies.components must be a declared eco component, same as on pages. Use explicit dependencies.components only when discovery cannot follow the import (export * barrels, packages).

How layouts are assigned

A Layout is only what a Page passes to eco.page({ layout }): one component or an outer-to-inner array. No file or folder name makes a module a Layout, and Ecopages does not wrap a Page in a layout.tsx or src/layouts/ file it does not reference. A view rendered with ctx.render() or app.static() takes its layout from its own eco.page({ layout }), so it renders the same as a filesystem Page.

Keep the layout where it is easiest to import. src/layouts/ is the convention for layouts shared across the site. A layout used by one section can sit beside its Pages as a Private File, such as src/pages/docs/_layout.tsx, imported by each Page of that section:

// src/pages/docs/getting-started.tsx
import { eco } from '@ecopages/core';
import { DocsLayout } from './_layout';

export default eco.page({
	layout: DocsLayout,
	render: () => <h1>Getting started</h1>,
});

The _ prefix keeps _layout.tsx out of routing. The name _layout has no other meaning, and a file with another private name works the same way.