Site Source Code and Runtime
Develop a Site with the Astro starter or a compatible HTTP application image, and use its authentication and runtime values.
Develop a Site's interface and server-side routes from an initialized Astro starter repository. Use Astro.locals for authentication configuration, the current Site User, and server-side logging.
Astro is optional. Any application image that implements the Site image contract can run with managed-site-worker. The starter implements that contract for you; the Astro guidance below describes its integration.
How the Site Repository and Runtime Work
The Astro starter supplies the application structure, authentication integration, and Dockerfile for Site hosting. Initialize it in a repository under your GitHub account or organization, following Develop the Application Locally.
The source repository is separate from the Site record: creating a Site does not inherently create a repository. A Site Worker binds the Site's authentication configuration to an application image built from your code.
This page documents the Contextual-specific repository and runtime contract. Use the public Astro documentation for general framework concepts and syntax.
Implement Backend APIs in Workers
Implement new backend API code in Workers. Keep endpoints with the UI in the Site Worker when their changes belong together. In one repository, UI and API code can share types and validation, developers and coding agents can follow a request from the page to its endpoint, and related changes can be tested in one local session and deployed in one application image.
The Astro starter supports server endpoints under src/pages/, as described in the repository contract. Other frameworks can serve APIs through the Site image contract.
Use a separate Worker when the backend needs independent deployment. For a managed HTTP backend, follow Build Your First Managed Worker and Platform Capabilities. Those handler capabilities are separate from the Site runtime values; the default Site application receives no platform SDK or tenant credentials, and its gateway exposes no Native Object API proxy.
Authenticate and Authorize API Requests
Enforce user, role, operation, and record access checks on the server before accessing data. Use the verified Site User from the request; do not trust a caller-supplied user ID, email, or role. Hiding UI controls does not restrict the corresponding API operation. A Site User role does not grant Contextual API permissions, and a backend Worker's platform identity does not establish the visitor's rights. See Site User Roles and Authorization.
With an Auth Profile configured, the Astro starter's middleware redirects signed-out requests to protected API routes to /sign-in before the handler runs. A browser fetch can follow that redirect and receive HTML. Handle the redirect, for example by checking response.redirected and directing the visitor to sign in, before parsing the response as JSON.
Exempting an external API or webhook route through public paths bypasses Site sign-in; the endpoint must still authenticate and authorize its callers. Signing in to a Site does not automatically authenticate requests to a separate Worker or another host. That endpoint must authenticate and authorize callers independently.
Work From the Initialized Repository
Work from your initialized repository, which already contains the Astro and Node adapter configuration that the Site runtime expects.
Use the Node.js version in .nvmrc, the package manager represented by yarn.lock, and the scripts in package.json. The current template uses Node.js 24 and Yarn. Treat the repository files as authoritative if a version in this documentation becomes outdated.
Understand the Repository Contract
The repository for a Contextual Site combines standard Astro files with Contextual-specific configuration.
| Path | Purpose | Normal Use |
|---|---|---|
src/pages/ |
Astro pages and routes, including server API endpoints and the standard sign-in and sign-out pages. | Add pages and backend API routes in the Site repository. For example, src/pages/api/orders.ts serves /api/orders. |
src/components/, src/scaffold/, and src/styles/ |
Reusable Astro components, Contextual's shared page layout, and styles. | Build the Site interface and shared layout. |
public/ |
Public assets that Astro copies without processing. | Add files that must keep their original form or filename. |
config.json |
Application public-path, session, and sign-in configuration. The build validates its shape. | Configure public paths, sessions, and sign-in methods, then build and deploy a new application image. |
package.json, .nvmrc, and yarn.lock |
Runtime version, dependencies, and repository commands. | Use the declared Node.js version and Yarn workflow. Review dependency changes through a pull request. |
astro.config.mjs |
Astro configuration for server output, the Node adapter, and build-time validation of config.json. |
Treat this as compatibility-sensitive runtime configuration. |
Dockerfile and docker/worker-shutdown.mjs |
Build the standalone Node server for a Site Worker and handle container shutdown. | Build the image from the repository root. Preserve the shutdown integration when changing the server startup command. |
src/middleware.ts |
Local authentication setup and route-level request middleware. | Change only when the Site requires a deliberate authentication-routing change. Test signed-in, signed-out, public, and error states. |
src/lib/astro-locals.ts and src/env.d.ts |
Types for the values available through Astro.locals. |
Use these types when reading runtime values. Keep them aligned with the Site runtime. |
site-auth.local.example.json and site-auth.local.json |
Example and local-only authentication configuration, including the Contextual CLI configuration used to resolve Site Users. | Copy the example when configuring local authentication. Never commit site-auth.local.json. |
.github/workflows/publish.yaml and, when included, .github/workflows/deploy.yaml |
Coordinate Version Packages, release publication, image builds, and optional deployment in Worker-enabled repositories. Earlier Publish workflows produce only the legacy tarball. | Review Changesets and the configured deployment behavior. See Deploy a Published Release for the Worker-enabled workflows, or use CLI image deployment. |
.github/workflows/template-sync.yaml, .templatesyncignore, and TEMPLATE_CHANGELOG.md |
Template-update workflow, application-specific exclusions, and upstream change notes. | Inspect the workflow's configured upstream and access; review and test updates through the normal pull request process. |
The Astro configuration, Dockerfile, authentication middleware, locals types, and standard authentication pages work together. Changing them can affect build compatibility, authentication, or container lifecycle behavior. Review and test those changes deliberately.
Distinguish Server Output and Middleware
The repository uses three related Astro concepts. They serve different purposes:
output: "server"inastro.config.mjstells Astro to render pages on demand by default. Read Astro's on-demand rendering guide for the framework behavior.mode: "standalone"in the@astrojs/nodeadapter produces the Node HTTP server used by a Site Worker. The starter selects this mode whenDEPLOYMENT=WORKER; its Dockerfile sets that value during the build. Read the@astrojs/nodeguide for the adapter behavior.src/middleware.tsis application request middleware. It reads the runtime values, handles local authentication, allows configured public paths, and redirects signed-out users. It runs within the Astro server. Read Astro's middleware guide for the framework API.
The build defaults to legacy AGENT mode when DEPLOYMENT is unset, which selects the Node adapter's middleware output. Check a Site Worker production build explicitly:
DEPLOYMENT=WORKER yarn build
The hosted application serves plain HTTP privately on 127.0.0.1:4321. The managed template's public gateway forwards requests to it and supplies the Site's authentication configuration and visitor identity. The template supplies readiness checks; the application does not need a custom health route. See Site Workers for deployment and verification.
Understand Local and Production Runtime Values
Local development and the hosted Site Worker expose the same three Astro.locals values through different sources. The starter constructs these values for each request. Treat them as request data, not global application state.
| Concern | Local Development | Hosted Site Worker |
|---|---|---|
| Astro server | yarn astro dev --host localhost starts the development server on your computer with the starter's local helper. |
The application image runs the standalone Node server built in Worker mode. |
| Authentication configuration | src/lib/dev.ts reads authConfig, ctxlConfigId, and disableAuth from site-auth.local.json. |
The gateway loads the bound Site's Auth Profile configuration and passes it to the application. |
| Site User | The helper decodes the session cookie's user ID and uses the signed-in Contextual CLI to resolve the Site User. | The gateway validates the session JWT for the Site's Stytch project, then resolves the Site User. |
| Logger | Asynchronous wrappers write to the development server's console. | Asynchronous wrappers write to the application container's console. |
| Application settings | Supply values to the local server's environment. | Supply runtime values through the Worker's Environment variables setting. |
The hosted gateway removes visitor-supplied copies of its identity headers before forwarding trusted configuration and identity. The starter already decodes and validates these headers into Astro.locals. Application code should use those locals for identity.
The local helper is for development only. It does not perform the hosted gateway's JWT validation. Follow Use an Auth Profile During Local Development to configure the ignored local file and CLI access. Disabling local authentication cannot verify protected-route behavior. Hosted settings follow Apply Site Configuration Changes; hosted Workers do not read site-auth.local.json.
Astro pages use Astro.locals; API endpoint handlers receive the same values through their locals context. The current runtime exposes these values:
| Value | Meaning |
|---|---|
Astro.locals.logger |
The asynchronous server logger, with debug, info, warn, and error methods backed by server-side console output. |
Astro.locals.authConfig |
The authentication configuration for a Site connected to an Auth Profile. It is undefined when the Site has no Auth Profile. Most Site code does not need to read it directly. |
Astro.locals.siteUser |
A Site User object when resolved; undefined when signed out, when there is no Auth Profile, or when the session is invalid; null when a valid session's Site User could not be found or created, including a backend error. Treat null as an error state. |
The default Site template supplies no platform SDK, platform client, or tenant credentials to application code. The gateway's platform access is used for authentication configuration and Site User resolution. Generic managed Worker APIs such as context.records and context.logger are not Astro APIs.
Write Server-Side Site Logs
Call the logger from the server-side frontmatter of an Astro page or component. Each method returns a promise, so await the call. The methods accept a format string and values:
---
const { logger, siteUser } = Astro.locals
await logger.info("Rendering the account page; siteUserResolved=%s", Boolean(siteUser))
---
<p>{siteUser ? `Signed in as ${siteUser.email}` : "Not signed in"}</p>
During local development, these messages appear in the terminal running the Astro server. When hosted, read the application's container output using the Worker logging commands.
Use the Site User Record
When authentication resolves a Site User, Astro.locals.siteUser contains:
| Field | Meaning |
|---|---|
id |
The Contextual Site User ID. |
externalId |
The identity provider's user ID. |
authProfileId |
The ID of the Auth Profile associated with the user. |
email |
The user's email address. |
name |
The user's name, when available. |
role |
The Site-level role: admin or member. Use this value as an input to application authorization; the runtime does not enforce route permissions from it. |
Read About Site Users before using this record for authorization decisions.
Keep Runtime Values on the Server
Server-side Astro frontmatter can read Astro.locals. A browser-side script cannot call Astro.locals.logger; calls to console in browser code appear only in the browser's developer console. They are separate from server container output.
Pass only the serializable fields that browser code needs. authConfig primarily supports the shared sign-in and user components, while most application code should use siteUser. Do not serialize the complete authentication configuration, copy Contextual CLI credentials into application files, or expose tokens, tenant credentials, or other shared secrets to the browser.
Configure Application Environment Variables
Use the Worker's Environment variables setting for application settings that vary between deployments or tenants. Values are injected at runtime. For secrets and file-based configuration, see Secrets and Configuration Files.
Server-side request code reads a named value through process.env. To verify runtime settings, add this harmless check to an Astro page's server-side frontmatter:
---
const configCheckPassed = process.env.SITE_CONFIG_CHECK === "ready"
await Astro.locals.logger.info("Site configuration check passed=%s", configCheckPassed)
---
- Build and deploy an application image containing the check.
- In the Worker's Environment variables setting, add
SITE_CONFIG_CHECKwith the valuereadyand save. Saving deploys a new Worker configuration; no new image is needed for this settings change. - Check the container output for
passed=true. - When verification is complete, remove the check from your code and deploy the updated image. Remove the variable from the Worker's environment too.
Once deployed code reads a variable, you can change its runtime value without rebuilding the image.
Hosted runtime values are not available to the application image build. Astro's import.meta.env values can be substituted at build time, and PUBLIC_ values can reach browser code. Keep credentials out of browser scripts, rendered HTML, and logs, and use only application variables you explicitly configure. Read the Astro environment-variable guide and the Node adapter's runtime guidance for the framework details.
Supply Values During Local Development
Local development does not inherit the Worker's environment. For bash or zsh, a local shell file can supply values to the Astro development server. Add site-env.local.sh to .gitignore before storing values in it, and confirm the rule with git check-ignore -v site-env.local.sh. The file can contain export SITE_CONFIG_CHECK='ready' for the harmless check above.
Load the file and start the server in a subshell:
(
. ./site-env.local.sh
yarn astro dev --host localhost
)
After changing the file, stop the server and repeat the command. Keep local secrets in the ignored file, outside command history and application images. The shell file is a local aid, not a deployed configuration file. Keep CLI authentication in the CLI configuration, and local authentication settings in the separate ignored site-auth.local.json file.
Configure Public Paths, Sessions, and Sign-In Methods
Edit config.json in the Site repository root to control which routes require sign-in and the session settings passed to the standard authentication components. These settings are part of the application build, so a hosted change requires a new application image and a Worker update. See Deploy and Update.
The template starts with no additional public routes and a static session duration of 30 days:
{
"publicPaths": [],
"sessions": {
"type": "static",
"duration": 30,
"unit": "days"
}
}
Choose Public Routes
With an Auth Profile configured, the standard middleware requires a Site User for routes outside publicPaths. /sign-in and /sign-out are always exempt from that check. A Site without an Auth Profile skips the standard sign-in requirement entirely.
To make an existing help page public, set publicPaths to ["/help"]. This allows signed-out visitors to open /help and /help/; it does not create the page. The field supports glob patterns, but explicit paths make the access change easier to review. A broad pattern can expose routes that were previously protected.
This check applies to application routes handled by the middleware. Files served as static assets are not protected by publicPaths; do not put private files in public/ or bundle them into browser assets.
Choose Session Settings
| Setting | Effect |
|---|---|
sessions.duration |
A positive number. The template converts it to minutes for the standard Stytch components. |
sessions.unit |
minutes, hours, or days. |
sessions.type: "static" |
Requests the configured duration at sign-in without enabling the starter user component's keep-alive option. This is the template default. |
sessions.type: "extend-with-use" |
Enables the keep-alive option passed to <cds-user> so use of the application can extend the longer Stytch session. Preserve that component integration on signed-in pages. |
Changing the configuration does not establish that existing sessions immediately receive a new expiry. Test the resulting sign-in and session behavior.
Keep Sessions Fresh on Every Page
The gateway authenticates requests from a short-lived session JWT. A Stytch client running in the browser refreshes that JWT from the longer session. Keep <cds-user> active on every signed-in page, including pages other than the home page; otherwise a visitor can be sent back through sign-in when the JWT expires.
The starter renders <cds-user> in src/pages/index.astro. To share it across signed-in pages, move it into src/scaffold/Layout.astro with its Site User, authentication configuration, and session settings. Remove the home-page copy and make sure each signed-in page uses that layout or renders the component itself. Other frameworks must keep their Stytch frontend SDK active for the same purpose.
JWT refresh and extending the longer session are separate behaviors. sessions.type controls whether use of the application extends that session; it does not add a browser client to custom pages. Test navigation and continued access across all protected pages when changing layouts or authentication components.
Choose Sign-In Methods
A Site signs users in with a magic link by default. Use that method with a Managed Stytch Auth Profile.
To offer an alternate method, such as Sign in with Google, connect the Site to a BYO Stytch Auth Profile whose Stytch project has that provider configured. Add the optional stytchConfig object to your existing config.json, preserving its other settings. For example:
{
"publicPaths": [],
"sessions": {
"type": "static",
"duration": 30,
"unit": "days"
},
"stytchConfig": {
"authMethods": ["google", "magic-link"]
}
}
That example offers both with Google displayed first. Setting the value to ["google"] alone disables magic links.
Supported methods differ between Stytch B2B and Consumer projects; see the StytchAuthMethod enum in src/config/index.ts. Omit stytchConfig when the Site uses Managed Stytch, or BYO Stytch with only magic links.
Validate and Release Configuration Changes
- Review the
config.jsondiff, especially any routes that become public. - From the repository root, run
DEPLOYMENT=WORKER yarn build. The build must succeed; it validates the configuration's shape, not the complete authentication flow. - Configure local authentication, then start the local server with
yarn astro dev --host localhost. - In a signed-out browser session, open a protected route and confirm that it redirects to
/sign-in. Check that each intended public route opens without signing in. - Sign in, confirm that the protected route opens, then sign out and check that it requires sign-in again. Test session-duration and renewal behavior on the pages that use the standard user component.
- Follow Deploy and Update to deploy the new application image on the intended Site Worker.
- Repeat the signed-out, signed-in, sign-out, public-route, and session checks on the hosted Site.
Upstream Template Updates
Site source initialization copies the public Astro Worker starter. Check .github/workflows/template-sync.yaml in your application repository before configuring updates.
If the workflow uses ContextualIO/template-sync-action@v1 with the starter's GitHub App configuration, it syncs from ContextualIO/astro-core-worker on the configured template branch. The tenant's GitHub Connection must cover the application repository, and the job needs id-token: write to exchange its GitHub Actions identity for a repository-scoped App token. See the template-sync Action.
Preserve the generated .template-sync-ref. The Action uses that commit to merge upstream changes and updates the file through sync pull requests. Review each pull request and its TEMPLATE_CHANGELOG.md notes, resolve conflicts, and retain application-specific exclusions in .templatesyncignore.
Install dependencies with yarn, run DEPLOYMENT=WORKER yarn build, and test affected local and hosted behavior, including authentication, before completing the update. Follow Deploy and Update to deploy reviewed changes. GitHub deployment access is covered separately in Deploy from GitHub.
Use Another Framework
Supply your image through the managed template's IMAGE option and bind the Site with SITE_ID. Your application must implement these serving, identity, and lifecycle requirements.
Serve Behind the Gateway
Listen for plain HTTP on 127.0.0.1:4321, using the supplied HOST and PORT values. The gateway forwards requests, responses, and WebSocket upgrades. Requests retain their path, query, body, cookies, and Host; the gateway adds no X-Forwarded-* headers. Visitors connect over HTTPS, so use HTTPS and the request's Host when constructing absolute public URLs.
The gateway forwards signed-out requests too. Your application must enforce protected routes and operation permissions. Readiness requires loaded Site configuration and an application accepting connections; no application health endpoint is required.
Read Identity and Implement Sign-In
The gateway removes visitor-supplied copies of these headers and supplies trusted values. Decode each present value as unpadded base64url containing UTF-8 JSON. Validate the expected fields and ignore unknown fields.
| Header | Decoded Value |
|---|---|
x-contextual-auth-config |
An object with string fields authProfileId, projectId, publicToken, and organizationSlug. The last field is empty for a Consumer project. Absent when the Site has no Auth Profile. |
x-contextual-site-user |
A Site User object, with string fields and an optional name, or JSON null when a valid session's user could not be resolved. An absent header means signed out. Treat null or malformed identity data as an error when handling protected requests. |
Use this identity for server-side authorization. The application receives no platform credentials or SDK from these headers.
Implement /sign-in with Stytch's frontend SDK using the public token and, for B2B, organization slug. The SDK must maintain the stytch_session_jwt cookie on the application's origin; the gateway reads that cookie to validate sessions. Sign out through the SDK to revoke the session and clear the cookie. Follow Authentication and Browser Origins for managed and BYO project registration.
Build and Shut Down the Container
Build for linux/amd64. Support user and group ID 10001, a read-only root filesystem, and temporary writes under /tmp. Follow the Worker runtime restrictions.
Handle SIGTERM in the application's main process and exit promptly. During shutdown the gateway stops accepting traffic and drains requests for up to 30 seconds before the application receives its signal. Verify startup, protected-route behavior, and shutdown with the application image before using it for a production deployment.