Skip to content

Open source website builder and Webflow alternative. Webstudio is an advanced visual builder that connects to any headless CMS, supports all CSS properties, and can be hosted anywhere, including with us.

feat: Add redirects UI for `301` redirects to external URL's (#2779)

Jaya Krishna Namburu11d7fa28ed33
diff --git a/apps/builder/app/builder/features/seo/project-redirects.tsx b/apps/builder/app/builder/features/seo/project-redirects.tsx
new file mode 100644
index 0000000000..910c87d447
--- /dev/null
+++ b/apps/builder/app/builder/features/seo/project-redirects.tsx
@@ -0,0 +1,217 @@
+import {
+ Grid,
+ Separator,
+ Flex,
+ InputField,
+ Button,
+ Text,
+ theme,
+ List,
+ ListItem,
+ SmallIconButton,
+ InputErrorsTooltip,
+} from "@webstudio-is/design-system";
+import { ArrowRightIcon, TrashIcon } from "@webstudio-is/icons";
+import { useState, type ChangeEvent } from "react";
+import type { ProjectSettings } from "./project-settings";
+import { PagePath, ProjectNewRedirectPathSchema } from "@webstudio-is/sdk";
+import { useStore } from "@nanostores/react";
+import { getExistingRoutePaths } from "../sidebar-left/panels/pages/page-utils";
+import { $pages } from "~/shared/nano-states";
+
+export const ProjectRedirectionSettings = (props: {
+ settings: ProjectSettings;
+ onSettingsChange: (settings: ProjectSettings) => void;
+}) => {
+ const [oldPath, setOldPath] = useState<string>("");
+ const [newPath, setNewPath] = useState<string>("");
+ const [oldPathErrors, setOldPathErrors] = useState<string[]>([]);
+ const [newPathErrors, setNewPathErrors] = useState<string[]>([]);
+ const pages = useStore($pages);
+ const existingPaths = getExistingRoutePaths(pages);
+
+ const redirects = props.settings?.redirects ?? [];
+ const redirectKeys = Object.keys(redirects);
+ const isValidRedirects =
+ oldPathErrors.length === 0 && newPathErrors.length === 0;
+
+ const handleOldPathChange = (event: ChangeEvent<HTMLInputElement>) => {
+ setOldPath(event.target.value);
+ setOldPathErrors(validateOldPath(event.target.value));
+ };
+
+ const handleNewPathChange = (event: ChangeEvent<HTMLInputElement>) => {
+ setNewPath(event.target.value);
+ setNewPathErrors(validateNewPath(event.target.value));
+ };
+
+ const validateOldPath = (oldPath: string): string[] => {
+ const oldPathValidationResult = PagePath.safeParse(oldPath);
+
+ if (oldPathValidationResult.success === true) {
+ if (oldPath.startsWith("/") === true) {
+ /*
+ This is the path, that users want to redirect to.
+ If the path already exists in the project. Then we can't add a redirect
+ */
+ if (existingPaths.has(oldPath) === true) {
+ return ["This path already exists in the project"];
+ }
+
+ if (redirects.some((redirect) => redirect.old === oldPath)) {
+ return ["This path is already being redirected"];
+ }
+ }
+ return [];
+ }
+
+ return oldPathValidationResult.error.format()?._errors;
+ };
+
+ const validateNewPath = (newPath: string): string[] => {
+ const newPathValidationResult =
+ ProjectNewRedirectPathSchema.safeParse(newPath);
+
+ if (newPathValidationResult.success === true) {
+ /*
+ This is the new path, that users want to redirect to.
+ If the new path doesn't exist, it's not a valid redirect.
+ */
+
+ if (newPath.startsWith("/") === true) {
+ if (existingPaths.has(newPath) === false) {
+ return ["This path doesn't exist in the project"];
+ }
+ }
+
+ return [];
+ }
+
+ return newPathValidationResult.error.format()._errors;
+ };
+
+ const handleOnKeyDown = (event: React.KeyboardEvent<HTMLInputElement>) => {
+ if (event.key === "Enter") {
+ handleAddRedirect();
+ }
+ };
+
+ const handleAddRedirect = () => {
+ const validOldPath = validateOldPath(oldPath);
+ const validNewPath = validateNewPath(newPath);
+
+ if (validOldPath.length > 0 || validNewPath.length > 0) {
+ return;
+ }
+
+ props.onSettingsChange({
+ ...props.settings,
+ redirects: [{ old: oldPath, new: newPath }, ...redirects],
+ });
+ setOldPath("");
+ setNewPath("");
+ };
+
+ const handleDeleteRedirect = (index: number) => {
+ const newRedirects = [...redirects];
+ newRedirects.splice(index, 1);
+ props.onSettingsChange({
+ ...props.settings,
+ redirects: newRedirects,
+ });
+ };
+
+ return (
+ <>
+ <Separator />
+ <Grid gap={2} css={{ mx: theme.spacing[5], px: theme.spacing[5] }}>
+ <Text variant="titles">301 Redirects</Text>
+ <Text color="subtle">
+ Redirects old URLs to new ones so that you don’t lose any traffic or
+ search engine rankings.
+ </Text>
+
+ <Flex gap="2" align="center">
+ <InputErrorsTooltip
+ errors={oldPathErrors.length > 0 ? oldPathErrors : undefined}
+ side="top"
+ css={{ zIndex: theme.zIndices["1"] }}
+ >
+ <InputField
+ type="text"
+ placeholder="/old-path"
+ value={oldPath}
+ css={{ flexGrow: 1 }}
+ onKeyDown={handleOnKeyDown}
+ onChange={handleOldPathChange}
+ color={oldPathErrors.length === 0 ? undefined : "error"}
+ />
+ </InputErrorsTooltip>
+ <ArrowRightIcon />
+
+ <InputErrorsTooltip
+ errors={newPathErrors.length > 0 ? newPathErrors : undefined}
+ side="top"
+ css={{ zIndex: theme.zIndices["2"] }}
+ >
+ <InputField
+ type="text"
+ placeholder="/new-path or URL"
+ value={newPath}
+ onKeyDown={handleOnKeyDown}
+ onChange={handleNewPathChange}
+ color={newPathErrors.length === 0 ? undefined : "error"}
+ />
+ </InputErrorsTooltip>
+
+ <Button
+ disabled={isValidRedirects === false || oldPath === newPath}
+ onClick={handleAddRedirect}
+ css={{ flexShrink: 0 }}
+ >
+ Add
+ </Button>
+ </Flex>
+ </Grid>
+
+ {redirectKeys.length > 0 ? (
+ <Grid
+ css={{
+ p: theme.spacing[5],
+ mx: theme.spacing[5],
+ }}
+ >
+ <List asChild>
+ <Flex direction="column" gap="1">
+ {redirects.map((redirect, index) => {
+ return (
+ <ListItem asChild key={redirect.old} index={index}>
+ <Flex
+ justify="between"
+ align="center"
+ gap="2"
+ css={{
+ p: theme.spacing[3],
+ }}
+ >
+ <Flex gap="2">
+ <Text>{redirect.old}</Text>
+ <ArrowRightIcon />
+ <Text truncate>{redirect.new}</Text>
+ </Flex>
+ <SmallIconButton
+ variant="destructive"
+ icon={<TrashIcon />}
+ onClick={() => handleDeleteRedirect(index)}
+ />
+ </Flex>
+ </ListItem>
+ );
+ })}
+ </Flex>
+ </List>
+ </Grid>
+ ) : null}
+ </>
+ );
+};
diff --git a/apps/builder/app/builder/features/seo/project-settings.tsx b/apps/builder/app/builder/features/seo/project-settings.tsx
index ae91ffe5f3..f19281506d 100644
--- a/apps/builder/app/builder/features/seo/project-settings.tsx
+++ b/apps/builder/app/builder/features/seo/project-settings.tsx
@@ -14,6 +14,7 @@ import {
css,
CheckboxAndLabel,
Checkbox,
+ ScrollArea,
} from "@webstudio-is/design-system";
import { useEffect, useState } from "react";
import { $isProjectSettingsOpen } from "~/shared/nano-states/seo";
@@ -25,9 +26,11 @@ import { useIds } from "~/shared/form-utils";
import { serverSyncStore } from "~/shared/sync";
import { useEffectEvent } from "../ai/hooks/effect-event";
import type { Pages } from "@webstudio-is/sdk";
+import { ProjectRedirectionSettings } from "./project-redirects";
+import { isFeatureEnabled } from "@webstudio-is/feature-flags";
type ProjectMeta = NonNullable<Pages["meta"]>;
-type ProjectSettings = NonNullable<Pages["settings"]>;
+export type ProjectSettings = NonNullable<Pages["settings"]>;
const imgStyle = css({
width: 72,
@@ -66,7 +69,6 @@ const ProjectSettingsContentMeta = (props: {
<Grid
gap={1}
css={{
- width: theme.spacing[34],
mx: theme.spacing[5],
px: theme.spacing[5],
}}
@@ -212,25 +214,34 @@ const ProjectSettingsView = () => {
// Left Aside panels (e.g., Pages, Components) use zIndex: theme.zIndices[1].
// For a dialog to appear above these panels, both overlay and content should also have zIndex: theme.zIndices[1].
css={{
+ width: theme.spacing[34],
zIndex: theme.zIndices[1],
}}
overlayCss={{
zIndex: theme.zIndices[1],
}}
>
- <Grid
- gap={2}
- css={{
- my: theme.spacing[5],
- }}
- >
- <ProjectSettingsContentMeta meta={meta} onMetaChange={setMeta} />
- <ProjectAdvancedSettings
- settings={settings}
- onSettingsChange={setSettings}
- />
- <div />
- </Grid>
+ <ScrollArea>
+ <Grid
+ gap={2}
+ css={{
+ my: theme.spacing[5],
+ }}
+ >
+ <ProjectSettingsContentMeta meta={meta} onMetaChange={setMeta} />
+ <ProjectAdvancedSettings
+ settings={settings}
+ onSettingsChange={setSettings}
+ />
+ {isFeatureEnabled("redirects") ? (
+ <ProjectRedirectionSettings
+ settings={settings}
+ onSettingsChange={setSettings}
+ />
+ ) : null}
+ <div />
+ </Grid>
+ </ScrollArea>
{/* Title is at the end intentionally,
* to make the close button last in the tab order
*/}
diff --git a/apps/builder/app/builder/features/sidebar-left/panels/pages/page-utils.test.ts b/apps/builder/app/builder/features/sidebar-left/panels/pages/page-utils.test.ts
index c451a3ad2c..292f5e8a5b 100644
--- a/apps/builder/app/builder/features/sidebar-left/panels/pages/page-utils.test.ts
+++ b/apps/builder/app/builder/features/sidebar-left/panels/pages/page-utils.test.ts
@@ -8,6 +8,7 @@ import {
reparentOrphansMutable,
toTreeData,
filterSelfAndChildren,
+ getExistingRoutePaths,
} from "./page-utils";
import { createDefaultPages } from "@webstudio-is/project-build";
import { isRoot, type Folder } from "@webstudio-is/sdk";
@@ -461,3 +462,33 @@ describe("filterSelfAndChildren", () => {
expect(result).toEqual([folders[2]]);
});
});
+
+describe("getExistingRoutePaths", () => {
+ const pages = createDefaultPages({
+ rootInstanceId: "rootInstanceId",
+ homePageId: "homePageId",
+ });
+
+ test("gets all the route paths that exists in the project", () => {
+ pages.pages.push({
+ id: "pageId",
+ meta: {},
+ name: "Page",
+ path: "/page",
+ rootInstanceId: "rootInstanceId",
+ title: "Page",
+ });
+
+ pages.pages.push({
+ id: "blogId",
+ meta: {},
+ name: "Blog",
+ path: "/blog/:id",
+ rootInstanceId: "rootInstanceId",
+ title: "Blog",
+ });
+
+ const result = getExistingRoutePaths(pages);
+ expect(Array.from(result)).toEqual(["/page", "/blog/:id"]);
+ });
+});
diff --git a/apps/builder/app/builder/features/sidebar-left/panels/pages/page-utils.ts b/apps/builder/app/builder/features/sidebar-left/panels/pages/page-utils.ts
index 34a7ab7a5b..a48c6d00a3 100644
--- a/apps/builder/app/builder/features/sidebar-left/panels/pages/page-utils.ts
+++ b/apps/builder/app/builder/features/sidebar-left/panels/pages/page-utils.ts
@@ -7,6 +7,7 @@ import {
ROOT_FOLDER_ID,
isRoot,
type WebstudioData,
+ getPagePath,
} from "@webstudio-is/sdk";
import { removeByMutable } from "~/shared/array-utils";
import { deleteInstanceMutable } from "~/shared/instance-utils";
@@ -261,3 +262,19 @@ export const filterSelfAndChildren = (
return folderIds.includes(folder.id) === false;
});
};
+
+export const getExistingRoutePaths = (pages?: Pages): Set<string> => {
+ const paths: Set<string> = new Set();
+ if (pages === undefined) {
+ return paths;
+ }
+
+ for (const page of pages.pages) {
+ const pagePath = getPagePath(page.id, pages);
+ if (pagePath === undefined) {
+ continue;
+ }
+ paths.add(pagePath);
+ }
+ return paths;
+};
diff --git a/packages/design-system/src/components/tooltip.tsx b/packages/design-system/src/components/tooltip.tsx
index 0087c17165..b3f549b198 100644
--- a/packages/design-system/src/components/tooltip.tsx
+++ b/packages/design-system/src/components/tooltip.tsx
@@ -125,10 +125,13 @@ Tooltip.displayName = "Tooltip";
export const InputErrorsTooltip = ({
errors,
children,
+ side,
+ css,
...rest
}: Omit<TooltipProps, "content"> & {
errors?: string[];
children: ComponentProps<typeof Tooltip>["children"];
+ side?: ComponentProps<typeof Tooltip>["side"];
}) => {
const content = errors?.map((error, index) => (
<Fragment key={index}>
@@ -145,7 +148,8 @@ export const InputErrorsTooltip = ({
{...rest}
content={content ?? " "}
open={errors !== undefined && errors.length !== 0}
- side="right"
+ side={side ?? "right"}
+ css={css}
>
{children}
</Tooltip>
diff --git a/packages/feature-flags/src/flags.ts b/packages/feature-flags/src/flags.ts
index 7ed1e877dd..163206b4ee 100644
--- a/packages/feature-flags/src/flags.ts
+++ b/packages/feature-flags/src/flags.ts
@@ -6,3 +6,4 @@ export const aiRadixComponents = false;
export const bindings = false;
export const cms = false;
export const folders = false;
+export const redirects = false;
diff --git a/packages/sdk/src/schema/pages.ts b/packages/sdk/src/schema/pages.ts
index 6d88d30d14..0bae45e3fe 100644
--- a/packages/sdk/src/schema/pages.ts
+++ b/packages/sdk/src/schema/pages.ts
@@ -102,11 +102,30 @@ const ProjectMeta = z.object({
code: z.string().optional(),
});
+export const ProjectNewRedirectPathSchema = PagePath.or(
+ z.string().refine((data) => {
+ try {
+ new URL(data);
+ return true;
+ } catch {
+ return false;
+ }
+ }, "Must be a valid URL")
+);
+
+export const PageRedirectSchema = z.object({
+ old: PagePath,
+ new: ProjectNewRedirectPathSchema,
+});
+
const ProjectSettings = z.object({
// All fields are optional to ensure consistency and allow for the addition of new fields without requiring migration
atomicStyles: z.boolean().optional(),
+ redirects: z.array(PageRedirectSchema).optional(),
});
+export type PageRedirect = z.infer<typeof PageRedirectSchema>;
+
export type ProjectMeta = z.infer<typeof ProjectMeta>;
export type Page = z.infer<typeof Page>;