Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: rewriting (experimental) #10867

Merged
merged 18 commits into from
May 8, 2024
Merged
Show file tree
Hide file tree
Changes from 11 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 51 additions & 0 deletions .changeset/pink-ligers-share.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
---
"astro": minor
---

Add experimental rewriting in Astro, via `rewrite()` function and `next()` function.
ematipico marked this conversation as resolved.
Show resolved Hide resolved

The feature is available via experimental flag:
ematipico marked this conversation as resolved.
Show resolved Hide resolved

```js
export default defineConfig({
experimental: {
rewriting: true
}
})
```

When enabled, you can use `rewrite()` to **render
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just checking on this formatting here. Did you mean to split up into two lines like this?

** another page without changing the URL of the browser in Astro pages and endpoints.

```astro
---
// src/pages/dashboard.astro
if (!Astro.props.allowed) {
return Astro.rewrite("/")
}
---
```

```js
// src/pages/api.js
export function GET(ctx) {
if (!ctx.locals.allowed) {
return ctx.rewrite("/")
}
}
```

The middleware `next()` function now accepts the same payload of the `rewrite()` function. For example, with `next("/")`, you can call the next middleware function with a new `Request`.
ematipico marked this conversation as resolved.
Show resolved Hide resolved

```js
// src/middleware.js
export function onRequest(ctx, next) {
if (!ctx.cookies.get("allowed")) {
return next("/") // new signature
}
return next();
}
```

> **NOTE
**: please [read the RFC](https://github.com/withastro/roadmap/blob/feat/reroute/proposals/0047-rerouting.md) to understand the current expectations of the new APIs.
104 changes: 102 additions & 2 deletions packages/astro/src/@types/astro.ts
Original file line number Diff line number Diff line change
Expand Up @@ -250,6 +250,19 @@ export interface AstroGlobal<
* [Astro reference](https://docs.astro.build/en/guides/server-side-rendering/)
*/
redirect: AstroSharedContext['redirect'];
/**
* It reroutes to another page. As opposed to redirects, the URL won't change, and Astro will render the HTML emitted
ematipico marked this conversation as resolved.
Show resolved Hide resolved
* by the rerouted URL passed as argument.
ematipico marked this conversation as resolved.
Show resolved Hide resolved
*
* ## Example
*
* ```js
* if (pageIsNotEnabled) {
* return Astro.reroute('/fallback-page')
ematipico marked this conversation as resolved.
Show resolved Hide resolved
* }
* ```
*/
rewrite: AstroSharedContext['rewrite'];
/**
* The <Astro.self /> element allows a component to reference itself recursively.
*
Expand Down Expand Up @@ -1641,7 +1654,7 @@ export interface AstroUserConfig {
domains?: Record<string, string>;
};

/** ⚠️ WARNING: SUBJECT TO CHANGE */
/** ! WARNING: SUBJECT TO CHANGE */
db?: Config.Database;

/**
Expand Down Expand Up @@ -1922,6 +1935,62 @@ export interface AstroUserConfig {
origin?: boolean;
};
};

/**
* @docs
* @name experimental.rewriting
* @type {boolean}
* @default `false`
* @version 4.8.0
* @description
*
* Enables a routing feature for rewriting requests in Astro pages, Endpoints and Astro middleware, giving you programmatic control over your routes.
ematipico marked this conversation as resolved.
Show resolved Hide resolved
*
ematipico marked this conversation as resolved.
Show resolved Hide resolved
* ```js
* {
* experimental: {
* rewriting: true,
* },
* }
* ```
*
* Use `Astro.rewrite` in your `.astro` files to reroute to a different page:
*
* ```astro "rewrite"
* ---
* // src/pages/dashboard.astro
* if (!Astro.props.allowed) {
* return Astro.rewrite("/")
* }
* ---
* ```
*
ematipico marked this conversation as resolved.
Show resolved Hide resolved
* Use `context.rewrite` in your endpoint files to reroute to a different page:
*
* ```js
* // src/pages/api.js
* export function GET(ctx) {
* if (!ctx.locals.allowed) {
* return ctx.rewrite("/")
* }
* }
* ```
*
* Use `next("/")` in your middleware file to reroute to a different page, and still call the next middleware function:
ematipico marked this conversation as resolved.
Show resolved Hide resolved
*
* ```js
* // src/middleware.js
* export function onRequest(ctx, next) {
* if (!ctx.cookies.get("allowed")) {
* return next("/") // new signature
* }
* return next();
* }
* ```
ematipico marked this conversation as resolved.
Show resolved Hide resolved
*
* For a complete overview, and to give feedback on this experimental API, see the [Rerouting RFC](https://github.com/withastro/roadmap/blob/feat/reroute/proposals/0047-rerouting.md).
*/
rewriting: boolean;
};
}

Expand Down Expand Up @@ -2491,6 +2560,20 @@ interface AstroSharedContext<
*/
redirect(path: string, status?: ValidRedirectStatus): Response;

/**
* It reroutes to another page. As opposed to redirects, the URL won't change, and Astro will render the HTML emitted
ematipico marked this conversation as resolved.
Show resolved Hide resolved
* by the rerouted URL passed as argument.
*
* ## Example
*
* ```js
* if (pageIsNotEnabled) {
* return Astro.reroute('/fallback-page')
ematipico marked this conversation as resolved.
Show resolved Hide resolved
* }
* ```
*/
rewrite(rewritePayload: RewritePayload): Promise<Response>;

/**
* Object accessed via Astro middleware
*/
Expand Down Expand Up @@ -2605,6 +2688,21 @@ export interface APIContext<
*/
redirect: AstroSharedContext['redirect'];

/**
* It reroutes to another page. As opposed to redirects, the URL won't change, and Astro will render the HTML emitted
* by the rerouted URL passed as argument.
*
* ## Example
*
* ```ts
* // src/pages/secret.ts
* export function GET(ctx) {
* return ctx.reroute(new URL("../"), ctx.url);
ematipico marked this conversation as resolved.
Show resolved Hide resolved
* }
* ```
*/
rewrite: AstroSharedContext['rewrite'];

/**
* An object that middlewares can use to store extra information related to the request.
*
Expand Down Expand Up @@ -2799,7 +2897,9 @@ export interface AstroIntegration {
};
}

export type MiddlewareNext = () => Promise<Response>;
export type RewritePayload = string | URL | Request;

export type MiddlewareNext = (reroutePayload?: RewritePayload) => Promise<Response>;
ematipico marked this conversation as resolved.
Show resolved Hide resolved
export type MiddlewareHandler = (
context: APIContext,
next: MiddlewareNext
Expand Down
52 changes: 7 additions & 45 deletions packages/astro/src/core/app/index.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,6 @@
import type {
ComponentInstance,
ManifestData,
RouteData,
SSRManifest,
} from '../../@types/astro.js';
import type { ManifestData, RouteData, SSRManifest } from '../../@types/astro.js';
import { normalizeTheLocale } from '../../i18n/index.js';
import type { SinglePageBuiltModule } from '../build/types.js';
import {
DEFAULT_404_COMPONENT,
REROUTABLE_STATUS_CODES,
REROUTE_DIRECTIVE_HEADER,
clientAddressSymbol,
Expand All @@ -26,7 +19,6 @@ import {
prependForwardSlash,
removeTrailingForwardSlash,
} from '../path.js';
import { RedirectSinglePageBuiltModule } from '../redirects/index.js';
import { RenderContext } from '../render-context.js';
import { createAssetLink } from '../render/ssr-element.js';
import { ensure404Route } from '../routing/astro-designed-error-pages.js';
Expand Down Expand Up @@ -96,7 +88,7 @@ export class App {
routes: manifest.routes.map((route) => route.routeData),
});
this.#baseWithoutTrailingSlash = removeTrailingForwardSlash(this.#manifest.base);
this.#pipeline = this.#createPipeline(streaming);
this.#pipeline = this.#createPipeline(this.#manifestData, streaming);
this.#adapterLogger = new AstroIntegrationLogger(
this.#logger.options,
this.#manifest.adapterName
Expand All @@ -110,18 +102,19 @@ export class App {
/**
* Creates a pipeline by reading the stored manifest
*
* @param manifestData
* @param streaming
* @private
*/
#createPipeline(streaming = false) {
#createPipeline(manifestData: ManifestData, streaming = false) {
if (this.#manifest.checkOrigin) {
this.#manifest.middleware = sequence(
createOriginCheckMiddleware(),
this.#manifest.middleware
);
}

return AppPipeline.create({
return AppPipeline.create(manifestData, {
logger: this.#logger,
manifest: this.#manifest,
mode: 'production',
Expand Down Expand Up @@ -309,7 +302,7 @@ export class App {
}
const pathname = this.#getPathnameFromRequest(request);
const defaultStatus = this.#getDefaultStatusCode(routeData, pathname);
const mod = await this.#getModuleForRoute(routeData);
const mod = await this.#pipeline.getModuleForRoute(routeData);

let response;
try {
Expand Down Expand Up @@ -405,7 +398,7 @@ export class App {

return this.#mergeResponses(response, originalResponse, override);
}
const mod = await this.#getModuleForRoute(errorRouteData);
const mod = await this.#pipeline.getModuleForRoute(errorRouteData);
try {
const renderContext = RenderContext.create({
locals,
Expand Down Expand Up @@ -493,35 +486,4 @@ export class App {
if (route.endsWith('/500')) return 500;
return 200;
}

async #getModuleForRoute(route: RouteData): Promise<SinglePageBuiltModule> {
if (route.component === DEFAULT_404_COMPONENT) {
return {
page: async () =>
({ default: () => new Response(null, { status: 404 }) }) as ComponentInstance,
renderers: [],
};
}
if (route.type === 'redirect') {
return RedirectSinglePageBuiltModule;
} else {
if (this.#manifest.pageMap) {
const importComponentInstance = this.#manifest.pageMap.get(route.component);
if (!importComponentInstance) {
throw new Error(
`Unexpectedly unable to find a component instance for route ${route.route}`
);
}
const pageModule = await importComponentInstance();
return pageModule;
} else if (this.#manifest.pageModule) {
const importComponentInstance = this.#manifest.pageModule;
return importComponentInstance;
} else {
throw new Error(
"Astro couldn't find the correct page to render, probably because it wasn't correctly mapped for SSR usage. This is an internal error, please file an issue."
);
}
}
}
}
Loading
Loading