Skip to content

Context quickstart

Share a value between a layout and a nested component.

View Markdown

Context passes values to nested Astro components without forwarding a prop through every intermediate component. It exists during a render; it is not a browser store or persistent session.

npm install @astro-utils/context
src/pages/index.astro
---
import Context from '@astro-utils/context/Context.astro';
const user = await fetchUser();
---
<Context contextName="user" {user}>
<Layout title="Home Page">
<h1>This is home page</h1>
<Button>This is your themed button!</Button>
</Layout>
</Context>
src/components/Button.astro
---
import getContext from '@astro-utils/context';
const { user } = getContext(Astro, 'user');
---
<button class={user?.themes?.button}>Click me</button>
src/layout/Website.astro
---
import getContext from '@astro-utils/context';
const { title } = Astro.props;
const { user } = getContext(Astro, 'user');
---
<html lang="en">
<head>
<title>{title}</title>
</head>
<body>
<p>{user ? "User logged in" : "User not logged in"}</p>
</slot>
</body>
</html>

A nested provider with the same contextName inherits the outer values and overrides the props it supplies (extends and override). An absent context returns {}.

See Context API for manual async rendering and the prop reference.