Context quickstart
Share a value between a layout and a nested component.
View MarkdownContext 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.
Install Context
Section titled “Install Context”npm install @astro-utils/contextbun add @astro-utils/contextpnpm add @astro-utils/contextyarn add @astro-utils/contextProvide a named value
Section titled “Provide a named value”---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>Every layout/component can use it
Section titled “Every layout/component can use it”---import getContext from '@astro-utils/context';const { user } = getContext(Astro, 'user');
---<button class={user?.themes?.button}>Click me</button>---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>Nested values
Section titled “Nested values”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.