Skip to content

The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:

Move embedding-specific rewrites to `metabase/embedding` (#75582)

Romeo Van Snickbf0ac23a9f3e
diff --git a/frontend/src/metabase/api/embed.ts b/frontend/src/metabase/api/embed.ts
index 8a10e27baa3..e0ea3b745c3 100644
--- a/frontend/src/metabase/api/embed.ts
+++ b/frontend/src/metabase/api/embed.ts
@@ -1,4 +1,3 @@
-import { getEmbedBase } from "metabase/services";
import type { CardId, DashCardId, Dataset } from "metabase-types/api";
import { Api } from "./api";
@@ -22,11 +21,11 @@ export type EmbedDashcardQueryRequest = {
export const embedApi = Api.injectEndpoints({
endpoints: (builder) => ({
getEmbedCardQuery: builder.query<Dataset, EmbedCardQueryRequest>({
- // `getEmbedBase()` is resolved per request so embed previews
- // (`/api/preview_embed`) hit the preview endpoints.
+ // `/api/embed` is rewritten to `/api/preview_embed` by the request
+ // middleware when running inside an embed preview.
query: ({ token, ...params }) => ({
method: "GET",
- url: `${getEmbedBase()}/card/${token}/query`,
+ url: `/api/embed/card/${token}/query`,
params,
}),
keepUnusedDataFor: 0,
@@ -34,7 +33,7 @@ export const embedApi = Api.injectEndpoints({
getEmbedCardQueryPivot: builder.query<Dataset, EmbedCardQueryRequest>({
query: ({ token, ...params }) => ({
method: "GET",
- url: `${getEmbedBase()}/pivot/card/${token}/query`,
+ url: `/api/embed/pivot/card/${token}/query`,
params,
}),
keepUnusedDataFor: 0,
@@ -42,7 +41,7 @@ export const embedApi = Api.injectEndpoints({
getEmbedDashcardQuery: builder.query<Dataset, EmbedDashcardQueryRequest>({
query: ({ token, dashcardId, cardId, ...params }) => ({
method: "GET",
- url: `${getEmbedBase()}/dashboard/${token}/dashcard/${dashcardId}/card/${cardId}`,
+ url: `/api/embed/dashboard/${token}/dashcard/${dashcardId}/card/${cardId}`,
params,
}),
keepUnusedDataFor: 0,
@@ -53,7 +52,7 @@ export const embedApi = Api.injectEndpoints({
>({
query: ({ token, dashcardId, cardId, ...params }) => ({
method: "GET",
- url: `${getEmbedBase()}/pivot/dashboard/${token}/dashcard/${dashcardId}/card/${cardId}`,
+ url: `/api/embed/pivot/dashboard/${token}/dashcard/${dashcardId}/card/${cardId}`,
params,
}),
keepUnusedDataFor: 0,
diff --git a/frontend/src/metabase/api/public.ts b/frontend/src/metabase/api/public.ts
index 06bf040e19f..7c03581f95f 100644
--- a/frontend/src/metabase/api/public.ts
+++ b/frontend/src/metabase/api/public.ts
@@ -1,4 +1,3 @@
-import { publicBase } from "metabase/services";
import type { CardId, DashCardId, Dataset } from "metabase-types/api";
import { Api } from "./api";
@@ -24,14 +23,14 @@ export type PublicDocumentCardQueryRequest = {
cardId: CardId;
};
-const PIVOT_PREFIX = `${publicBase}/pivot`;
+const PIVOT_PREFIX = "/api/public/pivot";
export const publicApi = Api.injectEndpoints({
endpoints: (builder) => ({
getPublicCardQuery: builder.query<Dataset, PublicCardQueryRequest>({
query: ({ uuid, ...params }) => ({
method: "GET",
- url: `${publicBase}/card/${uuid}/query`,
+ url: `/api/public/card/${uuid}/query`,
params,
}),
keepUnusedDataFor: 0,
@@ -47,7 +46,7 @@ export const publicApi = Api.injectEndpoints({
getPublicDashcardQuery: builder.query<Dataset, PublicDashcardQueryRequest>({
query: ({ uuid, dashcardId, cardId, ...params }) => ({
method: "GET",
- url: `${publicBase}/dashboard/${uuid}/dashcard/${dashcardId}/card/${cardId}`,
+ url: `/api/public/dashboard/${uuid}/dashcard/${dashcardId}/card/${cardId}`,
params,
}),
keepUnusedDataFor: 0,
@@ -72,7 +71,7 @@ export const publicApi = Api.injectEndpoints({
>({
query: ({ uuid, cardId }) => ({
method: "GET",
- url: `${publicBase}/document/${uuid}/card/${cardId}`,
+ url: `/api/public/document/${uuid}/card/${cardId}`,
}),
}),
}),
diff --git a/frontend/src/metabase/embedding/lib/override-requests-for-embeds.ts b/frontend/src/metabase/embedding/lib/override-requests-for-embeds.ts
index 31545d3e97d..66bd0d4e338 100644
--- a/frontend/src/metabase/embedding/lib/override-requests-for-embeds.ts
+++ b/frontend/src/metabase/embedding/lib/override-requests-for-embeds.ts
@@ -1,21 +1,21 @@
import { sessionPropertiesPath } from "metabase/api";
-import type { RequestMethod } from "metabase/api/client";
+import { type RequestMethod, api } from "metabase/api/client";
+import { isEmbedPreview } from "metabase/embedding/config";
import {
PLUGIN_API,
PLUGIN_CONTENT_TRANSLATION,
PLUGIN_EMBEDDING_SDK,
} from "metabase/plugins";
import type { OnBeforeRequestHandlerConfig } from "metabase/plugins/oss/api";
-import { getEmbedBase, internalBase, publicBase } from "metabase/services";
import type { CardId, DashboardId, ParameterId } from "metabase-types/api";
type EmbedType = "guest" | "static" | "public";
const getBaseUrlByEmbedType = (embedType: EmbedType): string =>
({
- guest: getEmbedBase(),
- static: getEmbedBase(),
- public: publicBase,
+ guest: "/api/embed",
+ static: "/api/embed",
+ public: "/api/public",
})[embedType];
const getIgnoreOverridePatterns = () => [
@@ -31,14 +31,14 @@ const getIgnoreOverridePatterns = () => [
* These patterns are needed only for endpoints that have different parameter names/path/structure for `/embed`
*/
const URL_PATTERNS = {
- CARD_QUERY: `${internalBase}/card/:cardId/query`,
- CARD_PIVOT_QUERY: `${internalBase}/card/pivot/:cardId/query`,
- CARD_PARAMETER_VALUES: `${internalBase}/card/:cardId/params/:paramId/values`,
- CARD_PARAMETER_SEARCH: `${internalBase}/card/:cardId/params/:paramId/search/:query`,
- CARD_PARAMETER_REMAPPING: `${internalBase}/card/:cardId/params/:paramId/remapping`,
- DASHBOARD_PARAMETER_VALUES: `${internalBase}/dashboard/:dashId/params/:paramId/values`,
- DASHBOARD_PARAMETER_SEARCH: `${internalBase}/dashboard/:dashId/params/:paramId/search/:query`,
- DASHBOARD_PARAMETER_REMAPPING: `${internalBase}/dashboard/:dashId/params/:paramId/remapping`,
+ CARD_QUERY: `/api/card/:cardId/query`,
+ CARD_PIVOT_QUERY: `/api/card/pivot/:cardId/query`,
+ CARD_PARAMETER_VALUES: `/api/card/:cardId/params/:paramId/values`,
+ CARD_PARAMETER_SEARCH: `/api/card/:cardId/params/:paramId/search/:query`,
+ CARD_PARAMETER_REMAPPING: `/api/card/:cardId/params/:paramId/remapping`,
+ DASHBOARD_PARAMETER_VALUES: `/api/dashboard/:dashId/params/:paramId/values`,
+ DASHBOARD_PARAMETER_SEARCH: `/api/dashboard/:dashId/params/:paramId/search/:query`,
+ DASHBOARD_PARAMETER_REMAPPING: `/api/dashboard/:dashId/params/:paramId/remapping`,
} as const;
/**
@@ -173,8 +173,8 @@ function replaceWithEmbedBase({
}): string {
const baseUrl = getBaseUrlByEmbedType(embedType);
- if (url.includes(internalBase) && !url.includes(baseUrl)) {
- return url.replace(internalBase, baseUrl);
+ if (url.includes("/api") && !url.includes(baseUrl)) {
+ return url.replace("/api", baseUrl);
}
return url;
@@ -224,12 +224,48 @@ const setupRemappingUrls = (embedType: EmbedType) => {
`${baseUrl}/card/:entityIdentifier/params/${encodeURIComponent(parameterId)}/remapping`;
};
+const EMBED_API_BASE_PATTERN = /^\/api\/embed(?=\/|$)/;
+const EMBED_PREVIEW_API_BASE = "/api/preview_embed";
+
+/**
+ * In an embed preview (Metabase iframed in itself) the embed endpoints live
+ * under `/api/preview_embed` instead of `/api/embed`. Rewriting the base here
+ * lets call sites hardcode `/api/embed` and stay preview-agnostic. The pattern
+ * is anchored at the start so only the base path is replaced.
+ */
+export const rewriteEmbedPreviewUrl = async ({
+ url,
+}: OnBeforeRequestHandlerConfig) => {
+ if (isEmbedPreview() && EMBED_API_BASE_PATTERN.test(url)) {
+ return { url: url.replace(EMBED_API_BASE_PATTERN, EMBED_PREVIEW_API_BASE) };
+ }
+};
+
+/**
+ * Registers the embed-preview rewrite on the shared client. It runs after the
+ * embed override handlers, so it covers both the override-produced
+ * `/api/embed/...` urls and the embed endpoints called directly (e.g.
+ * `EmbedApi`, `embedApi`).
+ *
+ * Idempotent, so call sites can register it at the earliest safe moment without
+ * worrying about duplicates. For public/static embeds it must run *before* the
+ * dashboard fetcher's effect (see `usePublicEndpoints`): React runs child
+ * effects before parent effects, so registering from a parent `useMount` would
+ * miss the very first embed request (the dashboard load).
+ */
+export const setupEmbedPreviewRewrite = () => {
+ if (!api.beforeRequestHandlers.includes(rewriteEmbedPreviewUrl)) {
+ api.beforeRequestHandlers.push(rewriteEmbedPreviewUrl);
+ }
+};
+
/**
* Registers a request interceptor that transforms standard API requests
* into guest embeds API requests.
*/
export const overrideRequestsForGuestEmbeds = () => {
setupRemappingUrls("guest");
+ setupEmbedPreviewRewrite();
PLUGIN_EMBEDDING_SDK.onBeforeRequestHandlers.overrideRequestsForGuestEmbeds =
(data) =>
diff --git a/frontend/src/metabase/embedding/lib/override-requests-for-embeds.unit.spec.ts b/frontend/src/metabase/embedding/lib/override-requests-for-embeds.unit.spec.ts
index edec2a11770..62dafdcfd49 100644
--- a/frontend/src/metabase/embedding/lib/override-requests-for-embeds.unit.spec.ts
+++ b/frontend/src/metabase/embedding/lib/override-requests-for-embeds.unit.spec.ts
@@ -1,8 +1,23 @@
+import { api } from "metabase/api/client";
+import { isEmbedPreview } from "metabase/embedding/config";
+
import {
matchUrlPattern,
overrideRequests,
+ rewriteEmbedPreviewUrl,
+ setupEmbedPreviewRewrite,
} from "./override-requests-for-embeds";
+jest.mock("metabase/embedding/config", () => ({
+ isEmbedPreview: jest.fn(),
+}));
+
+const mockIsEmbedPreview = jest.mocked(isEmbedPreview);
+
+afterEach(() => {
+ mockIsEmbedPreview.mockReset();
+});
+
describe("matchUrlPattern", () => {
it("should match URL with single parameter", () => {
expect(
@@ -134,3 +149,63 @@ describe("overrideRequests", () => {
expect(result.method).toBe("GET");
});
});
+
+describe("setupEmbedPreviewRewrite", () => {
+ // The embed route registers `usePublicEndpoints` on a parent of the dashboard
+ // fetcher, and React runs child effects before parent effects, so this must be
+ // called synchronously (not from an effect) to catch the first embed request.
+ it("registers rewriteEmbedPreviewUrl on the shared client, idempotently", () => {
+ const before = api.beforeRequestHandlers.filter(
+ (handler) => handler === rewriteEmbedPreviewUrl,
+ ).length;
+
+ expect(before).toBe(0);
+
+ setupEmbedPreviewRewrite();
+ setupEmbedPreviewRewrite();
+
+ const after = api.beforeRequestHandlers.filter(
+ (handler) => handler === rewriteEmbedPreviewUrl,
+ ).length;
+
+ expect(after).toBe(1);
+ });
+});
+
+describe("rewriteEmbedPreviewUrl", () => {
+ it("rewrites the embed base to the preview base inside an embed preview", async () => {
+ mockIsEmbedPreview.mockReturnValue(true);
+
+ const result = await rewriteEmbedPreviewUrl({
+ method: "GET",
+ url: "/api/embed/card/THE_TOKEN/query",
+ data: {},
+ });
+
+ expect(result).toEqual({ url: "/api/preview_embed/card/THE_TOKEN/query" });
+ });
+
+ it("leaves the url untouched outside an embed preview", async () => {
+ mockIsEmbedPreview.mockReturnValue(false);
+
+ const result = await rewriteEmbedPreviewUrl({
+ method: "GET",
+ url: "/api/embed/card/THE_TOKEN/query",
+ data: {},
+ });
+
+ expect(result).toBeUndefined();
+ });
+
+ it("leaves non-embed urls untouched inside an embed preview", async () => {
+ mockIsEmbedPreview.mockReturnValue(true);
+
+ const result = await rewriteEmbedPreviewUrl({
+ method: "GET",
+ url: "/api/card/1/query",
+ data: {},
+ });
+
+ expect(result).toBeUndefined();
+ });
+});
diff --git a/frontend/src/metabase/public/hooks/use-public-endpoints.tsx b/frontend/src/metabase/public/hooks/use-public-endpoints.tsx
index e558d0995d3..670956a9c90 100644
--- a/frontend/src/metabase/public/hooks/use-public-endpoints.tsx
+++ b/frontend/src/metabase/public/hooks/use-public-endpoints.tsx
@@ -1,6 +1,9 @@
import { useMount } from "react-use";
-import { overrideRequestsForPublicOrStaticEmbeds } from "metabase/embedding/lib/override-requests-for-embeds";
+import {
+ overrideRequestsForPublicOrStaticEmbeds,
+ setupEmbedPreviewRewrite,
+} from "metabase/embedding/lib/override-requests-for-embeds";
import { PLUGIN_CONTENT_TRANSLATION } from "metabase/plugins";
import type { EntityToken, EntityUuid } from "metabase-types/api/entity";
@@ -11,8 +14,19 @@ export const usePublicEndpoints = ({
uuid: EntityUuid;
token: EntityToken;
}) => {
+ const isPublic = Boolean(uuid);
+ const isEmbed = Boolean(token);
+
+ // Register synchronously during render rather than from the `useMount` below:
+ // the dashboard fetcher lives in a child whose effect fires before this
+ // parent's effects, so a `useMount` registration would miss the first embed
+ // request. The call is idempotent.
+ if (isEmbed) {
+ setupEmbedPreviewRewrite();
+ }
+
useMount(() => {
- if (uuid) {
+ if (isPublic) {
overrideRequestsForPublicOrStaticEmbeds("public");
} else if (token) {
PLUGIN_CONTENT_TRANSLATION.setEndpointsForStaticEmbedding(token);
diff --git a/frontend/src/metabase/services.js b/frontend/src/metabase/services.js
index 4ed97b85bde..a1b70fe1013 100644
--- a/frontend/src/metabase/services.js
+++ b/frontend/src/metabase/services.js
@@ -1,12 +1,4 @@
import { DELETE, GET, POST, PUT } from "metabase/api/legacy-client";
-import { isEmbedPreview } from "metabase/embedding/config";
-
-export const internalBase = "/api";
-export const publicBase = "/api/public";
-// use different endpoints for embed previews
-export function getEmbedBase() {
- return isEmbedPreview() ? "/api/preview_embed" : "/api/embed";
-}
export const ActivityApi = {
most_recently_viewed_dashboard: GET(
@@ -39,22 +31,24 @@ export const CollectionsApi = {
};
export const PublicApi = {
- action: GET(`${publicBase}/action/:uuid`),
+ action: GET(`/api/public/action/:uuid`),
executeDashcardAction: POST(
- `${publicBase}/dashboard/:dashboardId/dashcard/:dashcardId/execute`,
+ `/api/public/dashboard/:dashboardId/dashcard/:dashcardId/execute`,
),
- executeAction: POST(`${publicBase}/action/:uuid/execute`),
- card: GET(`${publicBase}/card/:uuid`),
- dashboard: GET(`${publicBase}/dashboard/:uuid`),
+ executeAction: POST(`/api/public/action/:uuid/execute`),
+ card: GET(`/api/public/card/:uuid`),
+ dashboard: GET(`/api/public/dashboard/:uuid`),
prefetchDashcardValues: GET(
- `${publicBase}/dashboard/:dashboardId/dashcard/:dashcardId/execute`,
+ `/api/public/dashboard/:dashboardId/dashcard/:dashcardId/execute`,
),
document: GET(`/api/public/document/:uuid`),
};
+// `/api/embed` is rewritten to `/api/preview_embed` by the request middleware
+// when running inside an embed preview.
export const EmbedApi = {
- card: GET(getEmbedBase() + "/card/:token"),
- dashboard: GET(getEmbedBase() + "/dashboard/:token"),
+ card: GET("/api/embed/card/:token"),
+ dashboard: GET("/api/embed/dashboard/:token"),
};
export const AutoApi = {