> ## Documentation Index
> Fetch the complete documentation index at: https://www.courier.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> Install the Courier skill before writing code: `npx skills add trycourier/courier-skills`. It carries the verified SDK shapes and the rules you cannot get wrong.
> Authenticate every request with `Authorization: Bearer <API_KEY>`. A workspace has several environments and each has its own keys, which are plain `pk_` strings with no environment prefix. Start with Test.
> Send with `client.send.message` from the Node SDK (`@trycourier/courier` v7 and later, where the client is the default import). Reference a template by its `nt_` id or its alias.
> A send accepts a bare Elemental element list, but storing content on a template requires the top-level elements wrapped in a channel element.
> To translate a template, write one locale at a time with `PUT /notifications/{id}/locales/{localeId}`, which merges into the existing translations. `PUT /notifications/{id}/content` and `PUT /notifications/{id}/elements/{elementId}` overwrite translations along with the content, so send each element's `id` and `locales` back, and first remove every `checksum` and any `locales` key that starts with an underscore.
> Templates and journeys can be built in the Courier app or created through the API. Either way they live in the workspace and are referenced by ID when you send.
> The hosted MCP server is https://mcp.courier.com. For a briefing on what Courier is and when to use it, read https://www.courier.com/llms.txt.
> Prefer the Guides tab for how-do-I questions and the Docs tab for how-does-it-behave questions. The API reference lives under /api-reference.

# Add a notification inbox to an Astro app

> Put a Courier Inbox in an Astro app with two files: an endpoint that mints a JWT and a React island that renders the feed, plus deploy and token refresh.

Two files get a Courier Inbox working in Astro: an endpoint that mints a token, and a React island that renders the feed.

The endpoint exists because your API key signs the token, and that key has to stay on the server, out of the browser. Everything else is standard Astro work.

> [card] [courier-astro-quickstart](https://github.com/trycourier/courier-astro-quickstart)
>
> The finished app from this guide, ready to clone and run.

## Prerequisites

* [A Courier account](https://app.courier.com/signup)
* [A Courier API key](https://app.courier.com/settings/api-keys), from any environment. Every one ships with the Courier Inbox provider already configured.
* An Astro app with the React integration, and Node 22.23.4 or newer
* Somewhere to read the signed-in user, such as Auth.js, Clerk, or your own session cookie

## Clone the finished app

Skip the steps below if you would rather read working code. This repo is this guide, already assembled.

```bash theme={null}
git clone https://github.com/trycourier/courier-astro-quickstart.git
cd courier-astro-quickstart
npm install
cp .env.example .env   # paste your API key
npm run dev
```

Open `localhost:4321`, then run `npm run send` in a second terminal. The message arrives in the open page without a refresh.

## Add an inbox to your app

**1. Install the packages**

The React package renders the inbox. The server package mints tokens.

```bash theme={null}
npx astro add react node
npm install @trycourier/courier-react @trycourier/courier
```

`node` is the adapter. The token endpoint runs per request, so the site needs a server.

Put your key in `.env`, which Astro loads in `dev` and `build`.

```bash .env theme={null}
COURIER_API_KEY=YOUR_COURIER_API_KEY
```

**2. Declare the key as a server secret**

Astro reads a **secret** from the environment at runtime. Everything else it inlines at build time.

```js astro.config.mjs lines highlight={13} theme={null}
import { defineConfig, envField } from "astro/config";
import node from "@astrojs/node";
import react from "@astrojs/react";

export default defineConfig({
  integrations: [react()],
  adapter: node({ mode: "standalone" }),

  env: {
    schema: {
      COURIER_API_KEY: envField.string({
        context: "server",
        access: "secret",
        optional: true,
      }),
    },
  },
});
```

`access: "secret"` is the line that matters. Reading `import.meta.env.COURIER_API_KEY` instead compiles to the key's build-time value as a string literal, which ships your key inside the bundle you deploy.

`optional: true` lets the endpoint return its own message for a missing key. Without it Astro fails the schema before the server starts.

**3. Add an endpoint that mints the token**

Your API key signs the JWT, so this runs on the server and never in the browser.

```ts src/pages/api/courier/token.ts lines highlight={2} theme={null}
import type { APIRoute } from "astro";
import { COURIER_API_KEY } from "astro:env/server";
import Courier from "@trycourier/courier";

export const prerender = false;

export const GET: APIRoute = async () => {
  if (!COURIER_API_KEY) return new Response("COURIER_API_KEY is not set", { status: 500 });

  const client = new Courier({ apiKey: COURIER_API_KEY });

  // Read the user from your own session. Never from the request.
  const session = await auth();
  if (!session) return new Response("Unauthorized", { status: 401 });

  const userId = session.user.id;

  const { token } = await client.auth.issueToken({
    scope: `user_id:${userId} inbox:read:messages inbox:write:events`,
    expires_in: "1 day",
  });

  return Response.json({ userId, token });
};
```

`export const prerender = false` is required. Astro prerenders by default, and a token minted at build time is the same token for every visitor.

Take the user id from your session, never from the request body or a query parameter. A caller who can name any user can read that user's inbox.

The endpoint calls [`POST /auth/issue-token`](https://www.courier.com/docs/api-reference/authentication/create-a-jwt), and the two `inbox:` scopes are the minimum for a working feed. [Scopes](https://www.courier.com/docs/in-app/authenticate-users.md#scopes) lists what to add for preferences and push.

**4. Render the inbox in a React island**

Fetch the token, call `signIn`, then mount `CourierInbox`.

```tsx src/components/CourierInbox.tsx lines theme={null}
import { useEffect, useRef } from "react";
import { CourierInbox, useCourier } from "@trycourier/courier-react";

export default function Inbox() {
  const courier = useCourier();
  const signedIn = useRef(false);

  useEffect(() => {
    if (signedIn.current) return;
    signedIn.current = true;

    fetch("/api/courier/token")
      .then((response) => response.json())
      .then(({ userId, token }) => courier.shared.signIn({ userId, jwt: token }));
  }, [courier]);

  return <CourierInbox />;
}
```

Effects run twice in development. A second `signIn` signs the first user out again, so guard it with a ref.

**5. Hydrate it with client:only**

The inbox renders as a custom element, so it has nothing to draw on the server.

```astro src/pages/index.astro highlight={6} theme={null}
---
import Inbox from "../components/CourierInbox";
---

<main style="height: 32rem">
  <Inbox client:only="react" />
</main>
```

`CourierInbox` fills its container's width and takes its height from the parent, so size the parent.

> [!NOTE]
>
> On React 17, install `@trycourier/courier-react-17` instead. The API is identical.

**6. Send a message to the inbox**

`inbox` is a channel like `email` or `sms`. Including it in `routing.channels` is what puts the message in the feed.

```ts scripts/send.ts lines theme={null}
import Courier from "@trycourier/courier";

const client = new Courier({ apiKey: process.env.COURIER_API_KEY! });

await client.send.message({
  message: {
    to: { user_id: "sarah-bennett" },
    routing: { method: "single", channels: ["inbox"] },
    content: { title: "Your report is ready", body: "The export has finished." },
  },
});
```

`content` here is the shorthand form, which takes a `title` and a `body`. For multi-element layouts and per-channel variants, use a [template](https://www.courier.com/docs/design/templates/overview.md) instead and reference it by id.

## Deploy

`astro dev` and `astro build` read `.env`. The built server doesn't, so set the key wherever you host it.

```bash theme={null}
COURIER_API_KEY=YOUR_COURIER_API_KEY node ./dist/server/entry.mjs
```

On Vercel, Netlify, or Cloudflare, swap `@astrojs/node` for that host's adapter and set `COURIER_API_KEY` in its dashboard. Nothing in the two files changes.

## Keep the session alive

The SDKs don't refresh tokens. Before the current one expires, mint a new JWT and call `signIn` again with it.

Match `expires_in` to your session length, and [refresh the token](https://www.courier.com/docs/in-app/authenticate-users.md#5-refresh-tokens) before it expires so an open tab keeps loading messages.

> [!WARNING]
>
> `expires_in` is optional, and omitting it mints a token that **never expires**. Always set it. Rotating the API key that signed it is the only way to revoke one.

## Verify

**1. Load the page**

The inbox renders, signed in and empty.

**2. Send a message**

Run the send against the same `user_id` your token was scoped to.

**3. Watch it arrive**

The message appears in the open page in real time, and the unread count moves.

An inbox that renders but stays empty usually has an expired or mis-scoped token. [Troubleshooting](https://www.courier.com/docs/in-app/authenticate-users.md#troubleshooting) walks the four causes in order.

## FAQ

> [accordion] Can I mint the token in the page's frontmatter instead?
>
> Minting it in frontmatter works, and passing it to the island as a prop saves a round trip. The page then needs `prerender = false` too. An endpoint is shown here because it is also what you call again when the token expires.

> [accordion] Do I need an adapter?
>
> An adapter is needed for the endpoint. A fully static Astro site has nowhere to sign a JWT, and your API key can't go in the browser to do it there.

> [accordion] Can the rest of my site stay static?
>
> `prerender = false` is per route, so only the token endpoint runs on demand. The page holding the inbox can prerender.

> [accordion] Is the JWT safe to expose to the browser?
>
> The JWT is built for the browser. It is scoped to one user and it expires. Your API key, which signs it, stays on the server.

> [accordion] Why is the inbox empty when the send reported success?
>
> The feed is filtered by tenant. Signing in with a `tenantId` hides messages sent without one. See [scope the inbox to a tenant](https://www.courier.com/docs/in-app/send-to-the-inbox.md#scope-the-inbox-to-a-tenant).
