Skip to content

Use a custom server

Liz Kenyon edited this page Apr 11, 2024 · 6 revisions

By default the Shopify App Remix template runs with the default Remix server, using remix-serve.

You can configure Remix apps to use a custom server.

The following provides an example using a custom Express server with the App Template

Add a server file

Add a server.js file to the root of your application.

Remix provides an example Express server, that can be modified slightly to work with the Shopify CLI. You must set the port to the FRONTEND_PORT environment variable set by the Shopify CLI.

// server.js
import { createRequestHandler } from "@remix-run/express";
import { installGlobals } from "@remix-run/node";
import compression from "compression";
import express from "express";
import morgan from "morgan";

installGlobals();

const viteDevServer =
  process.env.NODE_ENV === "production"
    ? undefined
    : await import("vite").then((vite) =>
        vite.createServer({
          server: { middlewareMode: true },
        })
      );

const remixHandler = createRequestHandler({
  build: viteDevServer
    ? () => viteDevServer.ssrLoadModule("virtual:remix/server-build")
    : await import("./build/server/index.js"),
});

const app = express();

app.use(compression());

// http://expressjs.com/en/advanced/best-practice-security.html#at-a-minimum-disable-x-powered-by-header
app.disable("x-powered-by");

// handle asset requests
if (viteDevServer) {
  app.use(viteDevServer.middlewares);
} else {
  // Vite fingerprints its assets so we can cache forever.
  app.use(
    "/assets",
    express.static("build/client/assets", { immutable: true, maxAge: "1y" })
  );
}

// Everything else (like favicon.ico) is cached for an hour. You may want to be
// more aggressive with this caching.
app.use(express.static("build/client", { maxAge: "1h" }));

app.use(morgan("tiny"));

// handle SSR requests
app.all("*", remixHandler);

+ // FRONTEND_PORT is set by the Shopify CLI
+ const port = process.env.FRONTEND_PORT;
app.listen(port, () =>
  console.log(`Express server listening at http://localhost:${port}`)
);

Update the shopify.web.toml

Update the command in the shopify.web.toml so that the shopify app dev CLI command will correctly start your Express server.

//shopify.web.toml

name = "remix"
roles = ["frontend", "backend"]
webhooks_path = "/webhooks"

[commands]
- dev = "npx prisma generate && npx prisma migrate deploy && npm exec remix vite:dev"
+ dev = "npx prisma generate && npx prisma migrate deploy && node server.js"

Update the vite.config.js

Update the vite.config.js so that the HMR server uses localhost

//vite.config.js

const hmrConfig = {
  protocol: "ws",
  host: "localhost",
  port: 64999,
  clientPort: 64999,
};

Note

The above setup HMR setup will only work while using the Chrome web browser.

Clone this wiki locally