{"_id":"@apostrophecms/apostrophe-astro-stable","_rev":"3-fbf59ed0e2fa64222e01d17d0cdf5cd0","name":"@apostrophecms/apostrophe-astro-stable","dist-tags":{"latest":"1.13.2"},"versions":{"1.13.0":{"name":"@apostrophecms/apostrophe-astro-stable","version":"1.13.0","author":{"name":"Apostrophe Technologies"},"license":"MIT","_id":"@apostrophecms/apostrophe-astro-stable@1.13.0","maintainers":[{"name":"alexgilbert","email":"alex@apostrophecms.com"},{"name":"boutell","email":"tom@apostrophecms.com"},{"name":"romanek","email":"stuart+npm@apostrophecms.com"},{"name":"bodonkey","email":"robert.means1969+apostrophecms@gmail.com"}],"homepage":"https://github.com/apostrophecms/apostrophe/tree/main/packages/apostrophe-astro#readme","bugs":{"url":"https://github.com/apostrophecms/apostrophe/issues"},"dist":{"shasum":"7ded51c1d05c03090fa41447a8314f0b7f4222b5","tarball":"https://registry.npmjs.org/@apostrophecms/apostrophe-astro-stable/-/apostrophe-astro-stable-1.13.0.tgz","fileCount":33,"integrity":"sha512-fibrWYe7uSt2KfSk2u46V0bbfSPqE2s3iLfkvFpYvMxeM1XYYwlFdc3Zjd6GyGBlKhXM3R8LPNl59G7vJgpD2g==","signatures":[{"sig":"MEQCIFmyAoBXhqwm310xF4Nqb/v8JZrOsbnOEl6xsEYhY5stAiA0JHzCim3u0PB0ekGmUir+7E9GEwsvXkjcylLoXTqlHQ==","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":124749},"main":"index.js","type":"module","gitHead":"b3e29f004f514041e1e389293ae67017c60d006e","_npmUser":{"name":"boutell","email":"tom@apostrophecms.com"},"repository":{"url":"git+https://github.com/apostrophecms/apostrophe.git","type":"git","directory":"packages/apostrophe-astro"},"_npmVersion":"11.6.1","description":"Apostrophe integration for Astro","directories":{},"_nodeVersion":"24.10.0","dependencies":{"sluggo":"npm:@apostrophecms/sluggo-stable@^1.0.0","undici":"^6.24.0","lodash.deburr":"^4.1.0"},"_hasShrinkwrap":false,"_npmOperationalInternal":{"tmp":"tmp/apostrophe-astro-stable_1.13.0_1781112757402_0.7570989155406931","host":"s3://npm-registry-packages-npm-production"}},"1.13.1":{"name":"@apostrophecms/apostrophe-astro-stable","version":"1.13.1","author":{"name":"Apostrophe Technologies"},"license":"MIT","_id":"@apostrophecms/apostrophe-astro-stable@1.13.1","maintainers":[{"name":"alexgilbert","email":"alex@apostrophecms.com"},{"name":"boutell","email":"tom@apostrophecms.com"},{"name":"romanek","email":"stuart+npm@apostrophecms.com"},{"name":"bodonkey","email":"robert.means1969+apostrophecms@gmail.com"}],"homepage":"https://github.com/apostrophecms/apostrophe/tree/main/packages/apostrophe-astro#readme","bugs":{"url":"https://github.com/apostrophecms/apostrophe/issues"},"dist":{"shasum":"f0209fd7c8df8833686270c087e8a60b2f312e8f","tarball":"https://registry.npmjs.org/@apostrophecms/apostrophe-astro-stable/-/apostrophe-astro-stable-1.13.1.tgz","fileCount":34,"integrity":"sha512-sMBuVHc/7GVExRgAPBowO1i2JoWh40XCSZ/TCJaADb76jf9Cs6dIBwlVkmg9a4vXr76PymglLXtiisK0M4jv/g==","signatures":[{"sig":"MEQCIC2/c3txK4whQQX3xmLB5xN+LE/wzTSNFvCvBlm/bX5KAiAFmvyUUU4VjnnnRPj2vTMIxu9L4i2bTtWq5TQvUsesJg==","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":131472},"main":"index.js","type":"module","gitHead":"1e81786e5f838973130ff476fd06547bf4fa67ab","_npmUser":{"name":"boutell","email":"tom@apostrophecms.com"},"repository":{"url":"git+https://github.com/apostrophecms/apostrophe.git","type":"git","directory":"packages/apostrophe-astro"},"_npmVersion":"11.16.0","description":"Apostrophe integration for Astro","directories":{},"_nodeVersion":"24.18.0","dependencies":{"sluggo":"npm:@apostrophecms/sluggo-stable@^1.0.0","undici":"^6.24.0","lodash.deburr":"^4.1.0"},"_hasShrinkwrap":false,"_npmOperationalInternal":{"tmp":"tmp/apostrophe-astro-stable_1.13.1_1783693439848_0.8389614480378413","host":"s3://npm-registry-packages-npm-production"}},"1.13.2":{"name":"@apostrophecms/apostrophe-astro-stable","version":"1.13.2","type":"module","description":"Apostrophe integration for Astro","repository":{"type":"git","url":"git+https://github.com/apostrophecms/apostrophe.git","directory":"packages/apostrophe-astro"},"homepage":"https://github.com/apostrophecms/apostrophe/tree/main/packages/apostrophe-astro#readme","main":"index.js","author":{"name":"Apostrophe Technologies"},"license":"MIT","dependencies":{"lodash.deburr":"^4.1.0","sluggo":"npm:@apostrophecms/sluggo-stable@^1.0.0","undici":"^6.24.0"},"gitHead":"ad1d0e830f7a7ddff1e721f37c421ab870add5dc","_id":"@apostrophecms/apostrophe-astro-stable@1.13.2","bugs":{"url":"https://github.com/apostrophecms/apostrophe/issues"},"_nodeVersion":"24.18.0","_npmVersion":"11.16.0","dist":{"integrity":"sha512-5Llw/25AL6Ac8idypn3ol6UzAo6pBRLLBTbl0Kdm67kYcZh501J36P263ztueqQN/ijrR5F4AzlA33mfxOJRHw==","shasum":"37f7a7b8a55a113a4a7406f93675e9b2b1c9c07d","tarball":"https://registry.npmjs.org/@apostrophecms/apostrophe-astro-stable/-/apostrophe-astro-stable-1.13.2.tgz","fileCount":34,"unpackedSize":132683,"signatures":[{"keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U","sig":"MEYCIQD/8UIRI9iJjJA3imApAAVpRpdrpUJfukOOiOxU6MBugAIhAITohphJ4w+eFCnR1BR1PVskHtf6i2yR9xC6s+2GuviF"}]},"_npmUser":{"name":"boutell","email":"tom@apostrophecms.com"},"directories":{},"maintainers":[{"name":"alexgilbert","email":"alex@apostrophecms.com"},{"name":"boutell","email":"tom@apostrophecms.com"},{"name":"romanek","email":"stuart+npm@apostrophecms.com"},{"name":"bodonkey","email":"robert.means1969+apostrophecms@gmail.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages-npm-production","tmp":"tmp/apostrophe-astro-stable_1.13.2_1786626796648_0.6455770379008616"},"_hasShrinkwrap":false}},"time":{"created":"2026-06-10T17:32:37.235Z","modified":"2026-08-13T13:13:16.970Z","1.13.0":"2026-06-10T17:32:37.527Z","1.13.1":"2026-07-10T14:24:00.000Z","1.13.2":"2026-08-13T13:13:16.792Z"},"bugs":{"url":"https://github.com/apostrophecms/apostrophe/issues"},"author":{"name":"Apostrophe Technologies"},"license":"MIT","homepage":"https://github.com/apostrophecms/apostrophe/tree/main/packages/apostrophe-astro#readme","repository":{"type":"git","url":"git+https://github.com/apostrophecms/apostrophe.git","directory":"packages/apostrophe-astro"},"description":"Apostrophe integration for Astro","maintainers":[{"name":"alexgilbert","email":"alex@apostrophecms.com"},{"name":"boutell","email":"tom@apostrophecms.com"},{"name":"romanek","email":"stuart+npm@apostrophecms.com"},{"name":"bodonkey","email":"robert.means1969+apostrophecms@gmail.com"}],"readme":"<div align=\"center\">\n  <img src=\"https://raw.githubusercontent.com/apostrophecms/apostrophe/main/logo.svg\" alt=\"ApostropheCMS logo\" width=\"80\" height=\"80\">\n\n  <h1>@apostrophecms/apostrophe-astro</h1>\n  <p>\n    <a aria-label=\"Apostrophe logo\" href=\"https://v3.docs.apostrophecms.org\">\n      <img src=\"https://img.shields.io/badge/MADE%20FOR%20ApostropheCMS-000000.svg?style=for-the-badge&logo=Apostrophe&labelColor=6516dd\">\n    </a>\n    <a aria-label=\"Join the community on Discord\" href=\"http://chat.apostrophecms.org\">\n      <img alt=\"\" src=\"https://img.shields.io/discord/517772094482677790?color=5865f2&label=Join%20the%20Discord&logo=discord&logoColor=fff&labelColor=000&style=for-the-badge&logoWidth=20\">\n    </a>\n  </p>\n</div>\n\n- [Astro integration for ApostropheCMS](#astro-integration-for-apostrophecms)\n  - [About Astro](#about-astro)\n  - [Bringing ApostropheCMS and Astro together](#bringing-apostrophecms-and-astro-together)\n  - [Installation](#installation)\n  - [Security](#security)\n  - [Configuration (Astro)](#configuration-astro)\n  - [Options](#options)\n    - [`aposHost` (mandatory)](#aposhost-mandatory)\n    - [`widgetsMapping` (mandatory)](#widgetsmapping-mandatory)\n    - [`templatesMapping` (mandatory)](#templatesmapping-mandatory)\n    - [`onBeforeWidgetRender` (optional)](#onbeforewidgetrender-optional)\n    - [`viewTransitionWorkaround` (optional)](#viewtransitionworkaround-optional)\n    - [`includeResponseHeaders`](#includeresponseheaders)\n    - [`excludeRequestHeaders`](#excluderequestheaders)\n    - [`forwardHeaders` (deprecated)](#forwardheaders-deprecated)\n    - [Mapping Apostrophe templates to Astro components](#mapping-apostrophe-templates-to-astro-components)\n    - [Mapping Apostrophe widgets to Astro components](#mapping-apostrophe-widgets-to-astro-components)\n    - [Creating the `[...slug.astro]` component and fetching Apostrophe data](#creating-the-slugastro-component-and-fetching-apostrophe-data)\n    - [Creating Astro page components](#creating-astro-page-components)\n    - [Creating Astro widget components](#creating-astro-widget-components)\n    - [Accessing image and URLs](#accessing-image-and-urls)\n  - [What to change in your Apostrophe project](#what-to-change-in-your-apostrophe-project)\n  - [Starting up your combined project](#starting-up-your-combined-project)\n  - [Logging in](#logging-in)\n  - [Redirections](#redirections)\n  - [404 Not Found](#404-not-found)\n  - [Reserved routes](#reserved-routes)\n  - [What about widget players?](#what-about-widget-players)\n  - [`aposSetQueryParameter`: working with query parameters](#apossetqueryparameter-working-with-query-parameters)\n  - [What about Vue, React, SvelteJS, etc.?](#what-about-vue-react-sveltejs-etc)\n  - [A note on production use](#a-note-on-production-use)\n  - [Debugging](#debugging)\n    - [Widget Render Hook](#widget-render-hook)\n  - [Enabling the `render-area` option to ApostropheCMS REST APIs](#enabling-the-render-area-option-to-apostrophecms-rest-apis)\n  - [Enabling the `@apostrophecms/layout-widget` in an existing project](#enabling-the-apostrophecmslayout-widget-in-an-existing-project)\n    - [Backend updates](#backend-updates)\n    - [Frontend updates](#frontend-updates)\n  - [Conclusion](#conclusion)\n  - [Acknowledgements](#acknowledgements)\n\n# Astro integration for ApostropheCMS\n\nThis module integrates ApostropheCMS into your [Astro](https://astro.build/) application.\n\n## About Astro\n\nAstro provides a \"universal bridge\" to run modern frontend frameworks like React, Vue,\nand SvelteJS on the server side, as well as a straightforward, JSX-like template\nlanguage of its own to meld everything together.\n\n## Bringing ApostropheCMS and Astro together\n\nThe intent of this integration is to let Apostrophe manage content, handle routing of URLs and fetch content,\nand let Astro take the responsibility for the rendering of pages\nand any associated logic using your framework(s) of choice like React, Vue.js,\nSvelte, etc. (see the [Astro integrations page](https://docs.astro.build/en/guides/integrations-guide/) for more).\n\n**This module also brings the ApostropheCMS Admin UI in your Astro application**, so you can manage your site exactly as if you were in a \"normal\" Apostrophe instance.\n\nWhen you use this module, you will have **two** projects:\n\n1. An Astro project. This is where you write your templates and frontend code.\n\n2. An Apostrophe project. This is where you define your page types, widget types\nand other content types with their schemas and other customizations.\n\nThis kind of dual-project CMS integration is typical for Astro.\n\nThe best way to keep everything consistent is to build these in `frontend` and `backend` subdirectories of the same git repository.\n\nTo get you started quickly, we recommend one of our official Astro starter kits:\n\n* [apostrophecms/starter-kit-astro-essentials](https://github.com/apostrophecms/starter-kit-astro-essentials) is best for a clean start with as little extra code as possible.\n* [apostrophecms/starter-kit-astro-apollo](https://github.com/apostrophecms/starter-kit-astro-apollo) is a full-fledged project with a blog, a design system and other nice touches.\n* [apostrophecms/starter-kit-astro-apollo-pro](https://github.com/apostrophecms/starter-kit-astro-apollo-pro) is great for those who expect to use our [Pro features](https://apostrophecms.com/pro) right away, but keep in mind you can add those modules to any project later.\n\n> 💡 These combined Astro + Apostrophe projects are best launched by forking the repository, not using our CLI. Follow the links to see how to fork these projects and get started on your own.\n\nYou can also adapt your own existing ApostropheCMS project as explained below.\n\n> Note that this module, `@apostrophecms/apostrophe-astro`, is meant to be installed as a dependency of your *Astro project*,\n> not your Apostrophe project.\n\nThis module is currently designed for use with Astro's `output: 'server'` setting (SSR mode), so that you can edit your content\ndirectly on the page. Support for export as a static site is under consideration for the future.\n\n## Installation\n\nIf you did not fork the sample projects above, you will need to install this\nmodule into your Astro project. Install this module in your\n**Astro project**, not your ApostropheCMS project:\n\n```shell\ncd my-astro-project\nnpm install @apostrophecms/apostrophe-astro\n```\n\n*Astro 3.x and 4.x are both supported.*\n\n## Security\n\nYou **must** set the `APOS_EXTERNAL_FRONT_KEY` environment variable to a secret\nvalue when running your Astro project, and also set the same variable to the same value when running your Apostrophe application.\nThis ensures that other sites on the web cannot fetch excessive amounts of\ninformation from ApostropheCMS without your permission.\n\n## Configuration (Astro)\n\nSince this is an Astro integration, you will need to add it to your Astro project's `astro.config.mjs` file.\nHere is a working `astro.config.mjs` file for a project with an Apostrophe CMS backend.\n\n```js\nimport { defineConfig } from 'astro/config';\nimport apostrophe from '@apostrophecms/apostrophe-astro';\n\n// For production. You can use other adapters that support\n// `output: 'server'`\nimport node from '@astrojs/node';\n\nexport default defineConfig({\n  output: 'server',\n  adapter: node({\n    mode: 'standalone'\n  }),\n  integrations: [\n    apostrophe({\n      aposHost: 'http://localhost:3000',\n      widgetsMapping: './src/widgets',\n      templatesMapping: './src/templates',\n      onBeforeWidgetRender: './src/hooks/before-widget-render.js', // Optional\n      viewTransitionWorkaround: false,\n      includeResponseHeaders: [\n        'content-security-policy',\n        'strict-transport-security',\n        'x-frame-options',\n        'referrer-policy',\n        'cache-control'\n      ],\n      excludeRequestHeaders: [\n        // For single-site setups or hosting on multiple servers, block the host header\n        'host'\n      ]\n      proxyRoutes: [\n        // Custom URLs that should be proxied to Apostrophe.\n        // Note that all of `/api/v1` is already proxied, so\n        // this is usually unnecessary\n      ]\n    })\n  ],\n  vite: {\n    ssr: {\n      // Do not externalize the @apostrophecms/apostrophe-astro plugin, we need\n      // to be able to use virtual: URLs there\n      noExternal: [ '@apostrophecms/apostrophe-astro' ],\n    }\n  }\n});\n```\n\n## Options\n\n### `aposHost` (mandatory)\n\nThis option is the base URL of your Apostrophe instance. It must contain the\nport number if testing locally and/or communicating directly with another instance\non the same server in a small production deployment. This option can be overriden\nat runtime with the `APOS_HOST` environment variable.\n\nDuring development it defaults automatically to: `http://localhost:3000`\n\n### `widgetsMapping` (mandatory)\n\nThe file in your project that contains the mapping between Apostrophe widget types and your Astro components (see below).\n\n### `templatesMapping` (mandatory)\n\nThe file in your project that contains the mapping between Apostrophe templates and your Astro templates (see below).\n\n### `onBeforeWidgetRender` (optional)\n\nPath to a hook function that runs before rendering widgets in edit mode. See [Widget Render Hook](#widget-render-hook) for details.\n\n### `viewTransitionWorkaround` (optional)\n\nIf set to `true`, Apostrophe will refresh its admin UI JavaScript on\nevery page transition, to ensure compatibility with Astro\n[view transitions](https://docs.astro.build/en/guides/view-transitions/).\nIf you are not using this feature of Astro, you can omit this flag to\nimprove performance for editors. Ordinary website visitors are\nnot impacted in any case. We are seeking an alternative solution to\neliminate this option.\n\n### `includeResponseHeaders`\n\nAn array of HTTP headers that you want to include from Apostrophe to the final response sent to the browser - useful if you want to use an Apostrophe module like `@apostrophecms/security-headers` and want to keep those headers as configured in Apostrophe and to preserve Apostrophe's caching headers.\n\nAt the present time, Astro is not compatible with the `nonce` property of `content-security-policy` `script-src` value. So this is automatically removed with that integration. The rest of the CSP header remains unchanged.\n\n### `excludeRequestHeaders`\n\nAn array of HTTP headers that you want to prevent from being forwarded from the browser to Apostrophe. This is particularly useful in single-site setups where you want to block the `host` header to allow Astro and Apostrophe to run on different hostnames.\n\nBy default, all headers are forwarded except those specified in this array.\n\n### `forwardHeaders` (deprecated)\n\nThis option has been replaced by `includeResponseHeaders` which provides clearer naming for its purpose. If both options are provided, `includeResponseHeaders` takes precedence. `forwardHeaders` will be removed in a future version.\n\n### Mapping Apostrophe templates to Astro components\n\nSince the front end of our project is entirely Astro, we'll need to create Astro components corresponding to each\ntemplate that Apostrophe would normally render with Nunjucks.\n\nCreate your template mapping in `src/templates/index.js` file.\nAs shown above, this file path must then be added to your `astro.config.mjs` file,\nin the `templatesMapping` option of the `apostrophe` integration.\n\n```js\n// src/templates/index.js\nimport HomePage from './HomePage.astro';\nimport DefaultPage from './DefaultPage.astro';\nimport BlogIndexPage from './BlogIndexPage.astro';\nimport BlogShowPage from './BlogShowPage.astro';\nimport NotFoundPage from './NotFoundPage.astro';\n\nconst templateComponents = {\n  '@apostrophecms/home-page': HomePage,\n  'default-page': DefaultPage,\n  '@apostrophecms/blog-page:index': BlogIndexPage,\n  '@apostrophecms/blog-page:show': BlogShowPage,\n  '@apostrophecms/page:notFound': NotFoundPage\n};\n\nexport default templateComponents;\n```\n\n#### How Apostrophe template names work\n\nFor ordinary page templates, like the home page or a typical \"default\" page type\nin an Apostrophe project, you can just specify the Apostrophe module name.\n\nFor special templates like `notFound`, and for modules that serve more than one\ntemplate, you'll need to specify the complete name. For instance, Apostrophe's\n`@apostrophecms/blog` module contains an `@apostrophecms/blog-page` page type\nthat renders an `index` template when viewing the main page of the blog, and\na `show` template when viewing a single blog post (a \"permalink\" page).\n\nIf you don't specify the template name, `:page` is assumed, which is just right\nfor ordinary page types.\n\nFor the \"404 Not Found\" page, use `@apostrophecms/page:notFound`, which is\nthe standard name for this template in ApostropheCMS.\n\n#### Special template names\n\nThe integration comes with two additional special template names that can be mapped to Astro templates.\nYou should not add a module name to these special names:\n\n* `apos-fetch-error`: served when Apostrophe generates a 500-class error. The integration will set Astro's response status to 500.\n* `apos-no-template`: served when there is no mapping corresponding to the Apostrophe page type for this page.\n\nSee below for an example Astro template for the `@apostrophe-cms/home-page` type. But first,\nlet's look at widgets.\n\n### Mapping Apostrophe widgets to Astro components\n\nSimilar to Astro page components, Astro widget components replace Apostrophe's usual\nwidget rendering.\n\nCreate your template mapping in a file in your application, for example in a\n`src/widgets/index.js` file. This file path must then be added to your `astro.config.mjs` file,\nin the `widgetsMapping` option of the `apostrophe` integration, as seen above.\n\n```js\n// src/widgets/index.js\n\nimport RichTextWidget from './RichTextWidget.astro';\nimport ImageWidget from './ImageWidget.astro';\nimport VideoWidget from './VideoWidget.astro';\nimport LayoutWidget from '@apostrophecms/apostrophe-astro/widgets/LayoutWidget.astro';\nimport LayoutColumnWidget from '@apostrophecms/apostrophe-astro/widgets/LayoutColumnWidget.astro';\n\nconst widgetComponents = {\n  // Standard widgets, but we must provide our own Astro components for them\n  '@apostrophecms/rich-text': RichTextWidget,\n  '@apostrophecms/image': ImageWidget,\n  '@apostrophecms/video': VideoWidget,\n  '@apostrophecms/layout': LayoutWidget,\n  '@apostrophecms/layout-column': LayoutColumnWidget\n};\n\nexport default widgetComponents;\n```\n\n> Note that even basic widget types like `@apostrophecms/image` do need an Astro\ntemplate in your project. This integration does not currently ship with built-in\nAstro templates for all of the common Apostrophe widgets. However, all of the starter kits referenced in this document include all the necessary code for the most common core widgets.\n\nNote that the Apostrophe widget name (on the left) is the name of your widget module **without**\nthe `-widget` part.\n\n> [!TIP]\n> The `@apostrophecms/layout-widget` needs some extra configuration and addition to areas in your ApostropheCMS project. You can read more in the [documentation](https://docs.apostrophecms.org/guide/core-widgets.html#layout-widget).\n\nThe naming of your Astro widget templates is up to you. The above convention is just\na suggestion.\n\n### Creating the `[...slug.astro]` component and fetching Apostrophe data\n\nSince Apostrophe is responsible for managing URLs to content, including creating new content and pages\non the fly, you will only need one top-level Astro page component: the `[...slug].astro` route.\n\nThe integration comes with an `aposPageFetch` method that can be used to automatically\nfetch the relevant data for the current URL.\n\nYour `[...slug].astro` component should look like this:\n\n```js\n---\nimport aposPageFetch from '@apostrophecms/apostrophe-astro/lib/aposPageFetch.js';\nimport AposLayout from '@apostrophecms/apostrophe-astro/components/layouts/AposLayout.astro';\nimport AposTemplate from '@apostrophecms/apostrophe-astro/components/AposTemplate.astro';\n\nconst aposData = await aposPageFetch(Astro.request);\nconst bodyClass = `myclass`;\n\nif (aposData.redirect) {\n  return Astro.redirect(aposData.url, aposData.status);\n}\nif (aposData.notFound) {\n  Astro.response.status = 404;\n}\n---\n<AposLayout title={aposData.page?.title} {aposData} {bodyClass}>\n    <Fragment slot=\"standardHead\">\n      <meta name=\"description\" content={aposData.page?.seoDescription} />\n      <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n      <meta charset=\"UTF-8\" />\n    </Fragment>\n    <AposTemplate {aposData} slot=\"main\" />\n</AposLayout>\n```\n\nThanks to the `aposPageFetch` call, the `aposData` object will then contain all of\nthe information normally provided by `data` in an ApostropheCMS Nunjucks template.\nThis includes, but is not limited to:\n\n* `page`: the page document for the current URL, if any\n* `piece`: the piece document when on a \"show page\" for a piece page type\n* `pieces`: an array of pieces when on an \"index page\" for a piece page type\n* `user`: information about the currently logged-in user\n* `global`: the ApostropheCMS global document e.g. global settings, editable global\nheaders and footers, etc.\n* `query`: the `req.query` object, giving access to query parameters in the URL.\n\nAny other data that your custom Apostrophe code attaches to `req.data` is also\navailable here.\n\n#### Understanding `AposLayout`\n\nThis integration comes with a full managed global layout, replacing the `outerLayout.html`\nused in Nunjucks page templates.\n\nIn your `[...slug].astro` file, use the `AposLayout` component built into this\nintegration to leverage the global layout.\n\nTo override any aspect of the global layout, take advantage of the following Astro slots,\nwhich are closely related to what ApostropheCMS offers in Nunjucks:\n\n* `startHead`: slot in the very beginning of the `<head>`\n* `standardHead`: slot in the middle of `<head>`, just after `<title>`\n* `extraHead`: still in the HTML `<head>`, at the very end\n* `startBody`: at the very beginning of the `<body>` - this is not part of the refresh zone in edit mode\n* `beforeMain`: at the very beginning of the main body zone - part of the refresh zone in edit mode\n* `main`: the inner part of the main body zone - part of the refresh zone in edit mode\n* `afterMain`: at the very end of the main body zone - part of the refresh zone in edit mode\n* `endBody`: at the very end of the `<body>` - this is not part of the refresh zone in edit mode\n\nIn addition, the `AposLayout` component expects four props:\n\n* `aposData`: the data fetched from Apostrophe\n* `title`: this will go in the `<title>` HTML tag\n* `lang` which will be set in the `<html>` `lang` attribute\n* `bodyClass`: this will be added in the `class` attribute of the `<body>` element\n\nThis layout component will automatically manage the switch between support for\nthe editing UI if a user is logged in and a simpler \"Run Layout\" for all other\npage requests.\n\n#### Understanding `AposTemplate`\n\nThe role of `AposTemplate` is to automatically find the right Astro component\nto render based on the template mapping you created earlier. It accepts one\nprop, the full `aposData` object.\n\n### Creating Astro page components\n\nNext we'll look at how to write Astro page components, such as the\n`src/templates/HomePage.astro` file mentioned above.\n\n> We do not recommend placing these in `src/pages` because their names are not\n> routes and Astro should not try to compile them as routes. Place them in\n> `src/templates` instead. `src/pages` should only contain the `[...slug.astro]` file.\n\nAs an example, let's take a look at a simple home page template:\n\n```js\n---\n// src/templates/HomePage.astro\nimport AposArea from '@apostrophecms/apostrophe-astro/components/AposArea.astro';\nconst { page } = Astro.props.aposData;\nconst { main } = page;\n---\n\n<section>\n  <h1>{ page.title }</h>\n  <AposArea area={main} />\n</section>\n```\n\nNotice that we receive the `page` object from Apostrophe, which gives us\naccess to `page.title`. This is similar to `data.page` in a Nunjucks template.\n\n#### Understanding the `AposArea` component\n\nThis component allows Astro to render Apostrophe areas, and provides a\nstandard Apostrophe editing experience when doing so. Astro will automatically\ncall our widget components once content exists in the area. All we have to do is\npass on the area object, in this case the `main` schema field of `page`.\n\nNote that we can also pass area objects that are schema fields of widgets.\nThis allows for nested widgets, such as multiple-column widgets often used\nfor page layout.\n\nNote that additional props can be passed to the `AposArea` component and will be made\naccessible to widget components.\n\n### Creating Astro widget components\n\nEarlier we created a mapping from Apostrophe widget names to Astro components.\nLet's take a look at how to implement these.\n\nYou Astro widget will receive a `widget` property, in addition to any custom props\nyou passed to the `AposArea` component. This `widget` property contains the\nthe schema fields of your Apostrophe widget.  \n\nAs an example, here is a simple Astro component to render `@apostrophecms/image` widgets:\n\n```js\n---\nconst { widget } = Astro.props;\nconst placeholder = widget?.aposPlaceholder;\nconst src = placeholder ?\n  '/images/image-widget-placeholder.jpg' :\n  widget?._image[0]?.attachment?._urls['full'];\n---\n<style>\n  .img-widget {\n    width: 100%;\n  }\n</style>\n<img class=\"img-widget\" {src} />\n```\n\n#### Placeholders are important in widgets that use them\n\nWhy are we checking for `aposPlaceholder`? Apostrophe's `@apostrophecms/image`\nwidget displays a placeholder image until the user clicks the edit pencil to\nselect their image of choice. When rendered by Astro, Apostrophe still expects\nthis to be the case. So we need to provide our own placeholder rendering.\n\nIn this case, a suitably named file must exist in `public/images` in our Astro project.\n\n#### Remember, relationship properties might not be populated\n\nIt is always possible that the image associated with an image widget has\nbeen archived. The `?.` syntax is a simple way to avoid a 500 error\nin such a situation. You may wish to add a more sophisticated fallback.\n\n### Accessing image and URLs\n\nProperties like `.attachment._urls['full']` exist on all image pieces,\nwhile properties like `.attachment._url` exist on non-image attachments\nsuch as PDFs. For more information, see\nthe [attachment field format](https://v3.docs.apostrophecms.org/reference/api/field-formats.html#attachment).\n\n## What to change in your Apostrophe project\n\nNothing! Well, almost.\n\n* Your project must be using Apostrophe 4.x.\n* You'll need to `npm update` your project to the latest version of `apostrophe`.\n* You'll need to set the `APOS_EXTERNAL_FRONT_KEY` environment variable to a secret\nvalue of your choosing when running Apostrphe.\n* Make sure you set that **same value** when running your Astro project.\n* To avoid developer confusion, we recommend changing any page templates in your\nApostrophe project to provide a link to your Astro frontend site and\nremove all other output. Everyone, editors included, should go straight to Astro.\n\n## Starting up your combined project\n\nTo start your Astro project, follow the usual practice:\n\n```bash\ncd my-astro-project\nnpm install\nexport APOS_EXTERNAL_FRONT_KEY=your-secret-goes-here\nnpm run dev\n```\n\nIn an adjacent terminal, start your Apostrophe project:\n\n```bash\ncd my-apostrophe-project\nnpm install\nexport APOS_EXTERNAL_FRONT_KEY=your-secret-goes-here\nnpm run dev\n```\n\nFor convenience, Astro generally defaults to port `4321`, while\nApostrophe defaults to port `3000`.\n\n## Logging in\n\nOnce your integration is complete, you will be able to reach the login page in\nthe usual way at `http://localhost:4321/login`. Astro proxies this route directly\nto Apostrophe. Therefore any additional extensions you have added such as\nApostrophe's hCaptcha and TOTP modules will work as expected.\n\n## Redirections\n\nWhen Apostrophe sends a response as a redirection, you will receive a specially\nformatted `aposData` object containing `redirect: true`, a `url` property for the url\nto redirect to, and a `status` for the redirection HTTP status code. This is handled\nin the earlier example, repeated here for convenience:\n\n```js\nconst aposData = await aposPageFetch(Astro.request)\n// Redirect\nif (aposData.redirect) {\n  return Astro.redirect(aposData.url, aposData.status);\n}\n```\n\n## 404 Not Found\n\nMuch like the redirect case, when Apostrophe determines that the page was not\nfound, `aposData.notFound` will be set to true. The example `[...slug].astro`\nfile provided above includes logic to set Astro's status code to 404 in this\nsituation.\n\n## Reserved routes\n\nAs this integration proxies certain Apostrophe endpoints, there are some routes that are taken by those endpoints:\n\n* `/apos-frontend/[...slug]` for serving Apostrophe assets\n* `/uploads/[...slug]` for serving Apostrophe uploaded assets\n* `/api/v1/[...slug]` and `/[locale]/api/v1/[...slug]` for Apostrophe API endpoints\n* `/login` and `/[locale]/login` for the login page\n\nAs all Apostrophe API endpoints are proxied, you can expose new api routes as usual in your Apostrophe modules, and be able to request them through your Astro application.\nThose proxies are forwarding all of the original request headers, such as cookies, so that Apostrophe login works normally.\n\n## What about widget players?\n\nApostropheCMS is very unopinionated on the front end, but it does include one\nimportant front end feature: widget players. These provide a way for developers\nto provide special behavior to widgets, calling each widget's player exactly\nonce at page load and when new widgets are inserted or replaced with new values.\nUsers appreciate this and expect interactive widget features to work normally\nwithout a page refresh, even if the widget was just added to the page.\n\nIn Astro, web components are a recommended strategy to achieve the same thing.\nDefining and using a web component in an Astro widget component has much\nthe same effect as defining a widget player in a standalone Apostrophe project.\n\nHere is a simple outline of such a web component. For a complete example of\nthe same widget, check out the source code of `VideoWidget.astro` in our\n[Astro Essentials Starter Kit](https://github.com/apostrophecms/starter-kit-astro-essentials/blob/main/frontend/src/widgets/VideoWidget.astro) project.\n\n```js\n---\n// src/widgets/VideoWidget.astro\nconst { widget } = Astro.props;\nconst placeholder = widget?.aposPlaceholder ? 'true' : '';\nconst url = widget?.video?.url;\n---\n<style>\n  video-widget {\n    width: 100%;\n  }\n</style>\n<video-widget\n  url={placeholder ? 'https://youtu.be/Q5UX9yexEyM' : url }\n>\n</video-widget>\n<script>\n  class VideoWidget extends HTMLElement {\n    constructor() {\n      super();\n      this.init();\n    }\n    async init() {\n      const videoUrl = this.getAttribute('url');\n      // Your logic here!\n      //\n      // Fetch details about the video URL,\n      // create an iframe to embed it, append it\n      // to the component's HTML element with this.append(),\n      // etc.\n    }\n  }\n  customElements.define('video-widget', VideoWidget);\n</script>\n```\n\n> Note that Astro script tags aren't really plain vanilla HTML script tags.\n> They are efficiently compiled, support TypeScript and are only executed\n> once even if the component appears may times on the page. Defining a\n> web component allows us to leverage that code more than once by using\n> the newly defined element as often as we wish.\n\n## `aposSetQueryParameter`: working with query parameters\n\nOne last thing: query parameters. Sometimes we want to create pagination\nlinks with page numbers, add filters to a URL's query string, and so on.\nBut, working with query parameters coming from Apostrophe can\nbe a little bit tricky because there are often special query parameters\npresent during editing that should not be part of a visible URL.\n\nAs a convenience, Apostrophe provides `aposSetQueryParameter` to abstract\nall that away.\n\nHere is how the `BlogIndexPage.astro` component of the\n[Starter Kit Astro Essentials](https://github.com/apostrophecms/starter-kit-astro-essentials/blob/main/frontend/src/templates/BlogIndexPage.astro) project generates\nlinks to each page of blog posts:\n\n```js\n---\nimport setParameter from '@apostrophecms/apostrophe-astro/lib/aposSetQueryParameter.js';\n\nconst {\n  pieces,\n  currentPage,\n  totalPages\n} = Astro.props.aposData;\n\nconst pages = [];\nfor (let i = 1; (i <= totalPages); i++) {\n  pages.push({\n    number: i,\n    current: page === currentPage,\n    url: setParameter(Astro.url, 'page', i)\n  });\n}\n---\n\n<section class=\"bp-content\">\n  <h1>{ page.title }</h1>\n\n  <h2>Blog Posts</h2>\n\n  {pieces.map(piece => (\n    <h3>\n      <a href={ piece._url }>{ piece.title }</a>\n    </h3>\n  ))}\n\n  {pages.map(page => (\n    <a\n      class={(page === currentPage) ? 'current' : ''} \n      href={page.url}>{page.number}\n    </a>\n  ))}\n</section>\n```\n\nImported here as `setParameter`, `aposSetQueryParameter` allows\nus to do two things:\n\n1. Take a URL and return a new URL with a certain query parameter set\nto a new value.\n2. Remove a query parameter completely by passing the empty string as\na value, or by passing `null` or `undefined`.\n\nWhile you can get the same result by manipulating `Astro.url` yourself,\nyou'll be able to avoid the confusing presence of query parameters\nlike `aposMode` by using this convenient feature.\n\n## What about Vue, React, SvelteJS, etc.?\n\nWhile not shown directly in the examples above, **Astro can import components\nwritten in any of these frameworks.** Just use `astro add` to install\nthe appropriate integration, then `import` your components freely in your\n`.astro` files. For complete documentation and examples, see the\n[`@astrojs/react` integration](https://docs.astro.build/en/guides/integrations-guide/react/).\n\nIn this way, Astro acts as a **universal bridge** to essentially all modern\nfrontend frameworks.\n\n## A note on production use\n\nFor production use, any Astro hosting adapter that supports `mode: 'server'` should\nbe acceptable. In particular, our [Starter Kit Astro Essentials](https://github.com/apostrophecms/starter-kit-astro-essentials) project comes pre-configured\nfor the `node` adapter, and includes `npm run build` and `npm run serve`\nsupport to take advantage of that. In `server` mode there is not a great\ndeal of difference between these and `npm run dev`, but there is less\noverhead and less information exposed to the public, so we recommend following\nthis best practice.\n\n## Debugging\n\nIn most cases, Astro prints helpful error messages directly in the browser\nwhen in a development environment.\n\nHowever, if you receive the following error:\n\n```\nOnly URLs with a scheme in: file and data are supported by the default ESM\nloader. Received protocol 'virtual:'\n```\n\nThen you most likely left out this part of the above `astro.config.mjs` file:\n\n```javascript\nexport default defineConfig({\n  // ... other settings above here ...\n  vite: {\n    ssr: {\n      // Do not externalize the @apostrophecms/apostrophe-astro plugin, we need\n      // to be able to use virtual: URLs there\n      noExternal: [ '@apostrophecms/apostrophe-astro' ],\n    }\n  }\n});\n```\n\nWithout this logic, the `virtual:` URLs used to access configuration information\nwill cause the build to fail.\n\n### Widget Render Hook\n\nWhen using patterns that require per-request initialization (like `AsyncLocalStorage` for request-scoped state), normal page rendering works fine because the page component can run setup code before rendering widgets. However, in edit mode, the widget render endpoint renders widgets directly without any extension point for initialization.\n\nThe `onBeforeWidgetRender` hook solves this by providing a function that runs before each widget renders in edit mode.\n\n**Setup**\n\nUsing this hook requires two steps: configuring the path in your integration options and creating the hook file.\n\n#### 1. Configure the Integration\n\nAdd the `onBeforeWidgetRender` option to your `astro.config.mjs`:\n```javascript\n// astro.config.mjs\nexport default defineConfig({\n  integrations: [\n    apostrophe({\n      widgetsMapping: './src/widgets',\n      templatesMapping: './src/templates',\n      onBeforeWidgetRender: './src/hooks/before-widget-render.js'\n    })\n  ]\n});\n```\n\n#### 2. Create the Hook File\n```javascript\n// src/hooks/before-widget-render.js\n/**\n * Runs before rendering each widget in edit mode\n * @param {Object} context.widget - The widget being rendered\n * @param {Object} context.props - Props including global data\n * @param {Object} context.Astro - Astro global object\n */\nexport default function({ widget, props, Astro }) {\n  // Your initialization logic\n  console.log('Rendering widget:', widget.type);\n}\n```\n#### Notes\n\n- The hook **only runs in edit mode** (when rendering via `/api/v1/@apostrophecms/area/render-widget`)\n- The hook can be synchronous or asynchronous (return a Promise)\n- Errors in the hook are logged but don't prevent widget rendering\n- The hook receives the same `props` that would be passed to the widget component\n\n## Enabling the `render-area` option to ApostropheCMS REST APIs\n\nIn order to enable section template library previews, and also unlock the `?render-area=1` and `?render-area=inline` query parameters to ApostropheCMS REST APIs in general, you'll need to add the following route:\n\n```markup\n---\n// Place this file in: src/pages/api/apos-external-front/render-area.astro\n\nimport AposRenderAreaForApi from '@apostrophecms/apostrophe-astro/components/AposRenderAreaForApi.astro';\n---\n<AposRenderAreaForApi />\n```\n\nThis file provides a \"bridge\" between ApostropheCMS and Astro, allowing ApostropheCMS to \"call back\" to the Astro project to render the content for a particular area.\n\nOur recently updated starter kits already include this file.\n\n## Enabling the `@apostrophecms/layout-widget` in an existing project\nIf you are using any of our starter kits, or you are following the integration steps outlined above, you will have the core layout-widget installed. For existing projects you will have a few steps to activate it.\n\n### Backend updates\n1. Add `@apostrophecms/layout` to any areas where you will want to add the widget.\n\nBy default, the layout widget columns will include the core rich-text, image, and video widgets. If you want any additional widget types, you will have to follow several additional steps:\n\n1. Create a `backend/modules/@apostrophecms/layout-column-widget/index.js` file.\n2. Add the following code:\n```javascript\nexport default {\n  fields(self, options) {\n    return {\n      add: {\n        content: {\n          type: 'area',\n          label: 'Main Content',\n          options: {\n            widgets: {\n              // add any project-specific content widgets\n              // nesting layout widgets can lead to poor performance\n              // or rendering issues\n              '@apostrophecms/rich-text': {},\n              '@apostrophecms/image': {},\n              '@apostrophecms/video': {}\n            }\n          }\n        }\n      }\n    };\n  }\n};\n```\n\nThis file extends the default column widget to define which content widgets editors can add inside each column. Avoid nesting layout widgets inside other layouts to prevent excessive DOM complexity and performance issues.\n\n> [!TIP]\n> You can read more about configuring and using the layout-widget in the [documentation](https://docs.apostrophecms.org/guide/core-widgets.html#layout-widget).\n\n### Frontend updates\nThe `@apostrophecms/apostrophe-astro` package contains templates for the layout widget and column, but like the other widgets, they have to be mapped to the corresponding Apostrophe widgets.\n\n1. Open the `frontend/src/widgets/index.js` file.\n2. Import the `layout` and `layout-column` widgets\n  ``` javascript\n    import LayoutWidget from '@apostrophecms/apostrophe-astro/widgets/LayoutWidget.astro';\n    import LayoutColumnWidget from '@apostrophecms/apostrophe-astro/widgets/LayoutColumnWidget.astro';\n  ```\n3. Map the components in the `widgetComponents` object\n  ``` javascript\n    export const widgetComponents = {\n    ...widgetComponents,\n    '@apostrophecms/layout': LayoutWidget,\n    '@apostrophecms/layout-column': LayoutColumnWidget\n  };\n  ```\nOnce you’ve added these mappings, restart your Apostrophe server and refresh the editor. The layout widget should now appear as an option in any area that includes @apostrophecms/layout.\n\n## Conclusion\n\nThis module provides a new way to use ApostropheCMS: as a back end\nfor modern front end development in Astro. But more than that, it\nprovides a future-proof bridge to many different front-end frameworks.\n\nAlso important, Apostrophe fully maintains the on-page, in-context editing\nexperience when integrated with Astro, going beyond \"side-by-side\"\nediting experiences to achieve integration close enough that we often\nhave to look at the address bar to know whether we are looking at\nAstro or Apostrophe.\n\nThat being said, this integration is also new, and we encourage you\nto share your feedback.\n\n## Acknowledgements\n\nDevelopment of this module began with Stéphane Maccari and Clément Ravier of\nMichelin. We are grateful for their generous support of ApostropheCMS.\n","readmeFilename":"README.md"}