Skip to content

This integration provides an import that exposes when in the lifecycle of an Astro codebase your code is running.

When/Where your code is running is made available as an exported constant, so you can change even the exported values of your modules based on it.

Installing the integration

This integration is needed during build time only, so you can install it as a dev dependency.

Terminal window
npx astro add @inox-tools/astro-when

How to use

Anywhere in your code, be it on a TypeScript file, an Astro component, an MDX file or any UI framework file, you can an import from @it-astro:when. This module exports the following:

  • An enum When defining the constant for each scenario your code might be running.
  • A constant whenAmI, which is a value of type When.

The possible values are:

  • When.Client: When your code is running on the client side.
  • When.Server: When your code is running on a prod server serving an SSR route.
  • When.Prerender: When your code is running during build to prerendeer a route on a project outputing for an SSR runtime.
  • When.StaticBuild: When your code is running during build to prerender a route on a project that is entirely static (no SSR adapter and output: 'static').
  • When.DevServer: When your code is running on the server during development.

Example

The following code demonstrate how to exposes a different Astro middleware depending on when the code is running:

import { whenAmI, When } from '@it-astro:when';
import type { MiddlewareHandler } from 'astro';
const middlewares: Record<When, MiddlewareHandler> = {
[When.Client]: () => {
throw new Error('Client should not run a middleware!');
},
[When.DevServer]: (_, next) => {
console.log('Running middleware on dev server');
return next();
},
[When.Server]: (_, next) => {
console.log('Running middleware on server for a server route');
return next();
},
[When.Prerender]: (_, next) => {
console.log('Running middleware while prerendering a route during build for an SSR output');
return next();
},
[When.StaticBuild]: (_, next) => {
console.log(
'Running middleware while rendering a route during build for a fully static output'
);
return next();
},
};
export const onRequest = middlewares[whenAmI];

For a project using this integration, including the example middleware above, check this example. You can also see it in action on a deployment of that project here.

License

Astro When is available under the MIT license.