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.

chore: Make code "Remix" friendly (#4005)

Ivan Starkov89e9748129de
diff --git a/apps/builder/app/auth/index.ts b/apps/builder/app/auth/index.client.ts
similarity index 100%
rename from apps/builder/app/auth/index.ts
rename to apps/builder/app/auth/index.client.ts
diff --git a/apps/builder/app/auth/login.tsx b/apps/builder/app/auth/login.tsx
index 9fa183bc69..13aede5edc 100644
--- a/apps/builder/app/auth/login.tsx
+++ b/apps/builder/app/auth/login.tsx
@@ -43,7 +43,7 @@ const sidebarStyle = css({
},
});
-type LoginProps = {
+export type LoginProps = {
errorMessage?: string;
isGithubEnabled?: boolean;
isGoogleEnabled?: boolean;
diff --git a/apps/builder/app/dashboard/dashboard.tsx b/apps/builder/app/dashboard/dashboard.tsx
index baf65f774c..f1b5210d3b 100644
--- a/apps/builder/app/dashboard/dashboard.tsx
+++ b/apps/builder/app/dashboard/dashboard.tsx
@@ -42,7 +42,7 @@ const Section = (props: ComponentProps<typeof Flex>) => {
);
};
-type DashboardProps = {
+export type DashboardProps = {
user: User;
projects: Array<DashboardProject>;
projectTemplates: Array<DashboardProject>;
diff --git a/apps/builder/app/dashboard/index.ts b/apps/builder/app/dashboard/index.client.ts
similarity index 100%
rename from apps/builder/app/dashboard/index.ts
rename to apps/builder/app/dashboard/index.client.ts
diff --git a/apps/builder/app/entry.client.tsx b/apps/builder/app/entry.client.tsx
index d9c65d5eec..3059a4dfb6 100644
--- a/apps/builder/app/entry.client.tsx
+++ b/apps/builder/app/entry.client.tsx
@@ -1,18 +1,8 @@
import { RemixBrowser } from "@remix-run/react";
import { startTransition, StrictMode } from "react";
-import { createRoot, hydrateRoot } from "react-dom/client";
+import { createRoot } from "react-dom/client";
startTransition(() => {
- if (document.documentElement.dataset.builder === "true") {
- hydrateRoot(
- document.getElementById("root")!,
- <StrictMode>
- <RemixBrowser />
- </StrictMode>
- );
- return;
- }
-
// Do not hydrate canvas, to avoid hydration Errors in case of 3rd party plugins.
// Just render it from scratch. (We don't have data on the Canvas at the server so no FOUC is possible)
const root = createRoot(document as never);
diff --git a/apps/builder/app/entry.server.tsx b/apps/builder/app/entry.server.tsx
index 424af2e611..f77af6be63 100644
--- a/apps/builder/app/entry.server.tsx
+++ b/apps/builder/app/entry.server.tsx
@@ -1,45 +1,84 @@
-import { renderToString } from "react-dom/server";
-import type { EntryContext } from "@remix-run/node";
+/**
+ * By default, Remix will handle generating the HTTP Response for you.
+ * You are free to delete this file if you'd like to, but if you ever want it revealed again, you can run `npx remix reveal` ✨
+ * For more information, see https://remix.run/file-conventions/entry.server
+ */
+
+import {
+ createReadableStreamFromReadable,
+ type AppLoadContext,
+ type EntryContext,
+} from "@remix-run/node";
import { RemixServer } from "@remix-run/react";
-import { handleRequest as handleRequestBuilder } from "./shared/remix/handle-request.server";
-import { isCanvas } from "./shared/router-utils";
+import { PassThrough } from "node:stream";
+import { renderToPipeableStream } from "react-dom/server";
+
+const ABORT_DELAY = 5_000;
-const handleRequestCanvas = (
+export default function handleRequest(
request: Request,
responseStatusCode: number,
responseHeaders: Headers,
- remixContext: EntryContext
-) => {
- const markup = renderToString(
- <RemixServer context={remixContext} url={request.url} />
+ remixContext: EntryContext,
+ // This is ignored so we can keep it in the template for visibility. Feel
+ // free to delete this parameter in your app if you're not using it!
+ _loadContext: AppLoadContext
+) {
+ return handleBrowserRequest(
+ request,
+ responseStatusCode,
+ responseHeaders,
+ remixContext
);
+}
- responseHeaders.set("Content-Type", "text/html");
-
- return new Response(`<!DOCTYPE html>${markup}`, {
- status: responseStatusCode,
- headers: responseHeaders,
- });
-};
-
-export default function handleRequest(
+// eslint-disable-next-line func-style
+function handleBrowserRequest(
request: Request,
responseStatusCode: number,
responseHeaders: Headers,
remixContext: EntryContext
) {
- let handle = handleRequestBuilder;
-
- // @todo canvas can be deployed as separate app
- // and separate request handler will not be necessary anymore
- if (
- remixContext.staticHandlerContext.matches.some(
- (match) => match.route.id === "routes/_index"
- ) &&
- isCanvas(request)
- ) {
- handle = handleRequestCanvas;
- }
-
- return handle(request, responseStatusCode, responseHeaders, remixContext);
+ return new Promise((resolve, reject) => {
+ let shellRendered = false;
+ const { pipe, abort } = renderToPipeableStream(
+ <RemixServer
+ context={remixContext}
+ url={request.url}
+ abortDelay={ABORT_DELAY}
+ />,
+ {
+ onShellReady() {
+ shellRendered = true;
+ const body = new PassThrough();
+ const stream = createReadableStreamFromReadable(body);
+
+ responseHeaders.set("Content-Type", "text/html");
+
+ resolve(
+ new Response(stream, {
+ headers: responseHeaders,
+ status: responseStatusCode,
+ })
+ );
+
+ pipe(body);
+ },
+ onShellError(error: unknown) {
+ reject(error);
+ },
+ onError(error: unknown) {
+ responseStatusCode = 500;
+ // Log streaming rendering errors from inside the shell. Don't log
+ // errors encountered during initial shell rendering since they'll
+ // reject and get logged in handleDocumentRequest.
+ if (shellRendered) {
+ console.error(error);
+ }
+ },
+ }
+ );
+
+ setTimeout(abort, ABORT_DELAY);
+ });
}
diff --git a/apps/builder/app/root.tsx b/apps/builder/app/root.tsx
index 6a670b0017..f624895be6 100644
--- a/apps/builder/app/root.tsx
+++ b/apps/builder/app/root.tsx
@@ -2,23 +2,17 @@
import { Outlet, json, useLoaderData } from "@remix-run/react";
import { setEnv } from "@webstudio-is/feature-flags";
import env from "./env/env.server";
-import type { ComponentProps } from "react";
import { useSetFeatures } from "./shared/use-set-features";
-type OutletProps = ComponentProps<typeof Outlet>;
-
export const loader = () => {
return json({
features: env.FEATURES,
});
};
-const Root = (props: OutletProps) => {
+export default function App() {
const { features } = useLoaderData<typeof loader>();
setEnv(features);
useSetFeatures();
-
- return <Outlet {...props} />;
-};
-
-export default Root;
+ return <Outlet />;
+}
diff --git a/apps/builder/app/routes/$.tsx b/apps/builder/app/routes/$.tsx
index 04e5b8005d..1fd91af89e 100644
--- a/apps/builder/app/routes/$.tsx
+++ b/apps/builder/app/routes/$.tsx
@@ -5,9 +5,9 @@ import {
type HeadersFunction,
} from "@remix-run/server-runtime";
import {
+ isRouteErrorResponse,
Links,
Meta,
- isRouteErrorResponse,
useLoaderData,
useRouteError,
} from "@remix-run/react";
@@ -106,7 +106,7 @@ const Content = () => {
<html lang="en">
<head>
<meta charSet="utf-8" />
- <meta name="viewport" content="width=device-width,initial-scale=1" />
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
<Meta />
<Links />
</head>
diff --git a/apps/builder/app/routes/builder.$projectId.tsx b/apps/builder/app/routes/_ui.builder.$projectId.tsx
similarity index 98%
rename from apps/builder/app/routes/builder.$projectId.tsx
rename to apps/builder/app/routes/_ui.builder.$projectId.tsx
index 7217f15803..73d2e41862 100644
--- a/apps/builder/app/routes/builder.$projectId.tsx
+++ b/apps/builder/app/routes/_ui.builder.$projectId.tsx
@@ -22,12 +22,13 @@ import {
import { createContext } from "~/shared/context.server";
import { ErrorMessage } from "~/shared/error";
import { loginPath } from "~/shared/router-utils";
-import type { BuilderProps } from "~/builder/index.client";
+
import env from "~/env/env.server";
import builderStyles from "~/builder/builder.css?url";
import prismStyles from "prismjs/themes/prism-solarizedlight.min.css?url";
import { ClientOnly } from "~/shared/client-only";
+import type { BuilderProps } from "~/builder/builder";
// Can cause FOUC because of remix-island, be very accurate adding anything here
export const links = () => {
@@ -156,7 +157,7 @@ const Builder = lazy(async () => {
return { default: Builder };
});
-export const BuilderRoute = () => {
+const BuilderRoute = () => {
const data = useLoaderData<BuilderProps>();
return (
diff --git a/apps/builder/app/routes/dashboard._index.tsx b/apps/builder/app/routes/_ui.dashboard._index.tsx
similarity index 78%
rename from apps/builder/app/routes/dashboard._index.tsx
rename to apps/builder/app/routes/_ui.dashboard._index.tsx
index 48c7a02057..f817fc4532 100644
--- a/apps/builder/app/routes/dashboard._index.tsx
+++ b/apps/builder/app/routes/_ui.dashboard._index.tsx
@@ -1,16 +1,18 @@
-import { type ComponentProps } from "react";
+import { lazy } from "react";
import { useLoaderData, useRouteError } from "@remix-run/react";
import { type LoaderFunctionArgs, redirect } from "@remix-run/server-runtime";
import { dashboardProjectRouter } from "@webstudio-is/dashboard/index.server";
-import { Dashboard } from "~/dashboard";
import { findAuthenticatedUser } from "~/services/auth.server";
import { loginPath } from "~/shared/router-utils";
import { ErrorMessage } from "~/shared/error";
import { createContext } from "~/shared/context.server";
import env from "~/env/env.server";
+import type { DashboardProps } from "~/dashboard/dashboard";
+import { ClientOnly } from "~/shared/client-only";
+
export const loader = async ({
request,
-}: LoaderFunctionArgs): Promise<ComponentProps<typeof Dashboard>> => {
+}: LoaderFunctionArgs): Promise<DashboardProps> => {
const user = await findAuthenticatedUser(request);
if (user === null) {
@@ -56,9 +58,19 @@ export const ErrorBoundary = () => {
return <ErrorMessage message={message} />;
};
+const Dashboard = lazy(async () => {
+ const { Dashboard } = await import("~/dashboard/index.client");
+ return { default: Dashboard };
+});
+
const DashboardRoute = () => {
- const data = useLoaderData<ReturnType<typeof loader>>();
- return <Dashboard {...data} />;
+ const data = useLoaderData<DashboardProps>();
+
+ return (
+ <ClientOnly>
+ <Dashboard {...data} />
+ </ClientOnly>
+ );
};
export default DashboardRoute;
diff --git a/apps/builder/app/routes/login._index.tsx b/apps/builder/app/routes/_ui.login._index.tsx
similarity index 80%
rename from apps/builder/app/routes/login._index.tsx
rename to apps/builder/app/routes/_ui.login._index.tsx
index 618211af1b..5eeab51677 100644
--- a/apps/builder/app/routes/login._index.tsx
+++ b/apps/builder/app/routes/_ui.login._index.tsx
@@ -1,4 +1,3 @@
-import type { ComponentProps } from "react";
import {
type LoaderFunctionArgs,
type TypedResponse,
@@ -8,10 +7,12 @@ import {
import { useLoaderData } from "@remix-run/react";
import { findAuthenticatedUser } from "~/services/auth.server";
import env from "~/env/env.server";
-import { Login } from "~/auth";
+import type { LoginProps } from "~/auth/index.client";
import { useLoginErrorMessage } from "~/shared/session";
import { dashboardPath } from "~/shared/router-utils";
import { returnToCookie } from "~/services/cookie.server";
+import { ClientOnly } from "~/shared/client-only";
+import { lazy } from "react";
const comparePathnames = (pathnameOrUrlA: string, pathnameOrUrlB: string) => {
const aPathname = new URL(pathnameOrUrlA, "http://localhost").pathname;
@@ -21,9 +22,7 @@ const comparePathnames = (pathnameOrUrlA: string, pathnameOrUrlB: string) => {
export const loader = async ({
request,
-}: LoaderFunctionArgs): Promise<
- TypedResponse<ComponentProps<typeof Login>>
-> => {
+}: LoaderFunctionArgs): Promise<TypedResponse<LoginProps>> => {
const user = await findAuthenticatedUser(request);
const url = new URL(request.url);
@@ -53,10 +52,19 @@ export const loader = async ({
);
};
+const Login = lazy(async () => {
+ const { Login } = await import("~/auth/index.client");
+ return { default: Login };
+});
+
const LoginRoute = () => {
const errorMessage = useLoginErrorMessage();
const data = useLoaderData<typeof loader>();
- return <Login {...data} errorMessage={errorMessage} />;
+ return (
+ <ClientOnly>
+ <Login {...data} errorMessage={errorMessage} />
+ </ClientOnly>
+ );
};
export default LoginRoute;
diff --git a/apps/builder/app/routes/vercel-deploy-workaround.tsx b/apps/builder/app/routes/_ui.tsx
similarity index 59%
rename from apps/builder/app/routes/vercel-deploy-workaround.tsx
rename to apps/builder/app/routes/_ui.tsx
index 147be7b203..4e0e00e30c 100644
--- a/apps/builder/app/routes/vercel-deploy-workaround.tsx
+++ b/apps/builder/app/routes/_ui.tsx
@@ -1,15 +1,15 @@
-import type { LinksFunction } from "@remix-run/server-runtime";
-
-import { Root } from "~/shared/remix/root";
+import {
+ Links,
+ Meta,
+ Outlet,
+ Scripts,
+ ScrollRestoration,
+} from "@remix-run/react";
import interFont from "@fontsource-variable/inter/index.css?url";
import manropeVariableFont from "@fontsource-variable/manrope/index.css?url";
import robotoMonoFont from "@fontsource/roboto-mono/index.css?url";
import appCss from "../shared/app.css?url";
-
-/**
- * For unknown reason vercel don't upload css assets if they are not exported from route path
- * This is workaround to make sure that all css assets we use in request handler are uploaded
- */
+import type { LinksFunction } from "@remix-run/server-runtime";
export const links: LinksFunction = () => {
// `links` returns an array of objects whose
@@ -22,4 +22,20 @@ export const links: LinksFunction = () => {
];
};
-export default Root;
+export default function Layout() {
+ return (
+ <html lang="en">
+ <head>
+ <meta charSet="utf-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
+ <Meta />
+ <Links />
+ </head>
+ <body>
+ <Outlet />
+ <ScrollRestoration />
+ <Scripts />
+ </body>
+ </html>
+ );
+}
diff --git a/apps/builder/app/routes/builder.tsx b/apps/builder/app/routes/builder.tsx
deleted file mode 100644
index 9b878b01cc..0000000000
--- a/apps/builder/app/routes/builder.tsx
+++ /dev/null
@@ -1,26 +0,0 @@
-import type { ServerRuntimeMetaFunction as MetaFunction } from "@remix-run/server-runtime";
-import { Root } from "~/shared/remix/root";
-import type { ShouldRevalidateFunction } from "@remix-run/react";
-
-export const meta: MetaFunction = () => {
- return [{ title: "Webstudio" }];
-};
-
-/**
- * We do not want trpc and other mutations that use the Remix useFetcher hook
- * to cause a reload of all builder data.
- */
-export const shouldRevalidate: ShouldRevalidateFunction = ({
- currentUrl,
- nextUrl,
- defaultShouldRevalidate,
-}) => {
- return currentUrl.href === nextUrl.href ? false : defaultShouldRevalidate;
-};
-
-export default Root;
-
-// Reduces Vercel function size from 29MB to 9MB for unknown reasons; effective when used in limited files.
-export const config = {
- maxDuration: 30,
-};
diff --git a/apps/builder/app/routes/dashboard.tsx b/apps/builder/app/routes/dashboard.tsx
deleted file mode 100644
index 685120bb45..0000000000
--- a/apps/builder/app/routes/dashboard.tsx
+++ /dev/null
@@ -1,13 +0,0 @@
-import type { ServerRuntimeMetaFunction as MetaFunction } from "@remix-run/server-runtime";
-import { Root } from "~/shared/remix/root";
-
-export const meta: MetaFunction = () => {
- return [{ title: "Webstudio Dashboard" }];
-};
-
-export default Root;
-
-// Reduces Vercel function size from 29MB to 9MB for unknown reasons; effective when used in limited files.
-export const config = {
- maxDuration: 30,
-};
diff --git a/apps/builder/app/routes/login.tsx b/apps/builder/app/routes/login.tsx
deleted file mode 100644
index 4e3d9c2cfc..0000000000
--- a/apps/builder/app/routes/login.tsx
+++ /dev/null
@@ -1,13 +0,0 @@
-import type { ServerRuntimeMetaFunction as MetaFunction } from "@remix-run/server-runtime";
-import { Root } from "~/shared/remix/root";
-
-export const meta: MetaFunction = () => {
- return [{ title: "Webstudio Login" }];
-};
-
-export default Root;
-
-// Reduces Vercel function size from 29MB to 9MB for unknown reasons; effective when used in limited files.
-export const config = {
- maxDuration: 30,
-};
diff --git a/apps/builder/app/routes/n8n.tsx b/apps/builder/app/routes/n8n.tsx
deleted file mode 100644
index 6590c7a342..0000000000
--- a/apps/builder/app/routes/n8n.tsx
+++ /dev/null
@@ -1,8 +0,0 @@
-import type { ServerRuntimeMetaFunction as MetaFunction } from "@remix-run/server-runtime";
-import { Root } from "~/shared/remix/root";
-
-export const meta: MetaFunction = () => {
- return [{ title: "Webstudio" }];
-};
-
-export default Root;
diff --git a/apps/builder/app/shared/empty.ts b/apps/builder/app/shared/empty.ts
new file mode 100644
index 0000000000..c50c6f4791
--- /dev/null
+++ b/apps/builder/app/shared/empty.ts
@@ -0,0 +1,5 @@
+// This module is intentionally left empty to prevent the import of certain libraries.
+// Specific libraries have been excluded from the project using Vite's alias configuration.
+// Any import that resolves to this module will return an empty object instead of the actual library.
+
+export default {};
diff --git a/apps/builder/app/shared/remix/handle-request.server.tsx b/apps/builder/app/shared/remix/handle-request.server.tsx
deleted file mode 100644
index d203bce57f..0000000000
--- a/apps/builder/app/shared/remix/handle-request.server.tsx
+++ /dev/null
@@ -1,52 +0,0 @@
-import { renderToString } from "react-dom/server";
-import { RemixServer } from "@remix-run/react";
-import type { EntryContext } from "@remix-run/node";
-import { flushCss } from "@webstudio-is/design-system";
-import { renderHeadToString } from "remix-island";
-import { Head } from "./root";
-import { links } from "~/routes/vercel-deploy-workaround";
-
-export const handleRequest = (
- request: Request,
- responseStatusCode: number,
- responseHeaders: Headers,
- remixContext: EntryContext
-) => {
- const markup = renderToString(
- <RemixServer context={remixContext} url={request.url} />
- );
-
- const head = renderHeadToString({ request, remixContext, Head });
-
- responseHeaders.set("Content-Type", "text/html");
- responseHeaders.set("Accept-CH", "Sec-CH-Prefers-Color-Scheme");
-
- // data-builder="true" to distinguish between builder and canvas at the entry.client.tsx
- // inject fonts and base body styles here instead of `export links = ` to avoid FOUC
- const body = `
- <!DOCTYPE html>
- <html lang="en" data-builder="true">
- <head>
- <meta charSet="utf-8" />
- <meta name="viewport" content="width=device-width,initial-scale=1" />
- ${links()
- .map((link) =>
- "href" in link
- ? `<link rel="${link.rel}" href="${link.href}" />`
- : ""
- )
- .join("\n")}
- ${head}
- <style id="stitches">${flushCss()}</style>
- </head>
- <body>
- <div id="root">${markup}</div>
- </body>
- </html>
- `;
-
- return new Response(body, {
- status: responseStatusCode,
- headers: responseHeaders,
- });
-};
diff --git a/apps/builder/app/shared/remix/root.tsx b/apps/builder/app/shared/remix/root.tsx
deleted file mode 100644
index 8d04b005d3..0000000000
--- a/apps/builder/app/shared/remix/root.tsx
+++ /dev/null
@@ -1,23 +0,0 @@
-import { Links, Meta, Outlet as RemixOutlet, Scripts } from "@remix-run/react";
-import { createHead } from "remix-island";
-
-/**
- * use remix-island to fix hydration errors when extensions
- * change layout, see https://github.com/webstudio-is/webstudio/pull/1621
- */
-export const Head = createHead(() => (
- <>
- <Meta />
- <Links />
- </>
-));
-
-export const Root = ({ Outlet = RemixOutlet }) => {
- return (
- <>
- <Head />
- <Outlet />
- <Scripts />
- </>
- );
-};
diff --git a/apps/builder/package.json b/apps/builder/package.json
index 02653fe78a..788ed33025 100644
--- a/apps/builder/package.json
+++ b/apps/builder/package.json
@@ -105,7 +105,6 @@
"remix-auth-form": "^1.5.0",
"remix-auth-github": "^1.7.0",
"remix-auth-google": "^2.0.0",
- "remix-island": "^0.2.0",
"shallow-equal": "^3.1.0",
"slugify": "^1.6.6",
"strip-indent": "^4.0.0",
diff --git a/apps/builder/vite.config.ts b/apps/builder/vite.config.ts
index d8a2c01f66..9fda34aea6 100644
--- a/apps/builder/vite.config.ts
+++ b/apps/builder/vite.config.ts
@@ -29,6 +29,12 @@ export default defineConfig(({ mode }) => {
find: "~",
replacement: resolve("app"),
},
+
+ // before 2,899.74 kB, after 2,145.98 kB
+ {
+ find: "@supabase/node-fetch",
+ replacement: resolve("./app/shared/empty.ts"),
+ },
],
},
define: {
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 7445d27336..2fcd2eb042 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -388,9 +388,6 @@ importers:
remix-auth-google:
specifier: ^2.0.0
- remix-island:
- specifier: ^0.2.0
shallow-equal:
specifier: ^3.1.0
version: 3.1.0
@@ -8775,14 +8772,6 @@ packages:
'@remix-run/react': ^1.0.0 || ^2.0.0
'@remix-run/server-runtime': ^1.0.0 || ^2.0.0
- resolution: {integrity: sha512-NujWtmulgupxNOMiWKAj8lg56eYsy09aV/2pML8rov8N8LmY1UnSml4XYad+KHLy/pgZ1D9UxAmjI6GBJydTUg==}
- peerDependencies:
- '@remix-run/react': '>= 1'
- '@remix-run/server-runtime': '>= 1'
- react: 18.3.0-canary-14898b6a9-20240318
- react-dom: 18.3.0-canary-14898b6a9-20240318
-
resolution: {integrity: sha512-8g3/Otx1eJaVD12e31UbJj1YzdtVvzH85HV7t+9MJYk/u3XmkOUJ5Ys9wQrf9PCPK8+xn4ymzqYCiZl6QWKn+A==}
@@ -17827,13 +17816,6 @@ snapshots:
'@remix-run/server-runtime': 2.11.0([email protected])
uuid: 8.3.2
- dependencies:
- '@remix-run/server-runtime': 2.11.0([email protected])
- react: 18.3.0-canary-14898b6a9-20240318
- react-dom: 18.3.0-canary-14898b6a9-20240318([email protected])
-