Skip to content

Cut-Short Requests

Cut-short is an Astro integration that lets you stop processing a request instantly and send back a custom response, simplifying control flow in your Astro applications. By introducing the endRequest function, it eliminates the need for cumbersome workarounds like bubbling up response objects, throwing and catching sentinel errors, implementing custom middleware logic or replicating error response logic across all your pages.

Keep the the custom response for specific conditions close to the conditions and have it shared across all your application. It’s especially useful for scenarios like user authentication and access control, where you might need to redirect users to sign-in page from anywhere that requires authentication or to turn any page they don’t have access to into a 404 to avoid information leak (like GitHub does).

Installing the integration

Terminal window
npx astro add @inox-tools/cut-short

How to use

From any code that is reachable from a page rendering context can use the endRequest function to stop the.

A page-rendering context is when you are inside of:

  • A middleware;
  • The frontmatter of a page component (not components in the page, see streaming);
  • An API endpoint;
  • A function called from another page-rendering context.
src/lib/auth.js
import { endRequest } from '@it-astro/cut-short';
export function getUser() {
if (noUser) endRequest(new Response('No user', { status: 401 }));
return {...};
}

endRequest()

Type: (withResponse: Response | (() => Response | Promise<Response>)) => void

Stop the current request and send back a custom response.

The argument can be a Response object to be used directly or a function that returns a Response object or a promise that resolves to a Response.

Streaming

Once Astro executes the frontmatter of the page component, the HTML response is streamed to the client as it is rendered. This means that when the frontmatter of components deep in the page is executed the response has already been partially sent. In the example below, when MyComponent is executed, the response has already been constructed and is being streamed.

src/pages/index.astro
---
import MyComponent from '../components/MyComponent.astro';
---
<html>
<head>
<title>Example</title>
</head>
<body>
<MyComponent />
</body>
</html>

This prevents components from changing the status code of the response and from completely switching the response under some condition. For that reason, calling endRequest from a component in the page is not allowed, just like returning a response:

src/components/MyComponent.astro
---
import { endRequest } from '@it-astro/cut-short';
// Neither of these is allowed
endRequest(new Response('Page not found', { status: 404 }));
return new Response('Page not found', { status: 404 });
---

License

Cut-Short Requests is available under the MIT license.