next.config.mjs

Anonymous
JavaScript
11/17/2026 8:10 AM
8.9 KB
5
No Index
Never
import createNextIntlPlugin from "next-intl/plugin";
import withPWAInit from "@ducanh2912/next-pwa";
import { fileURLToPath } from "node:url";
import { createRequire } from "node:module";
import { copyFileSync, mkdirSync, writeFileSync } from "node:fs";
import path from "node:path";
import { withSentryConfig } from "@sentry/nextjs";
import { PRIVATE_LINK_HEADERS, PRIVATE_PAGE_URL } from "./src/lib/payment-link-privacy.mjs";

// Serve the already-built PDF.js module worker as a versioned same-origin asset.
const require = createRequire(import.meta.url);
const pdfjs = require("pdfjs-dist/package.json");
const pdfWorkerDirectory = fileURLToPath(
  new URL(`./public/pdfjs/${pdfjs.version}/`, import.meta.url),
);
mkdirSync(pdfWorkerDirectory, { recursive: true });
copyFileSync(
  require.resolve("pdfjs-dist/legacy/build/pdf.worker.min.mjs"),
  path.join(pdfWorkerDirectory, "pdf.worker.min.js"),
);
copyFileSync(
  require.resolve("pdfjs-dist/legacy/build/pdf.min.mjs"),
  path.join(pdfWorkerDirectory, "pdf.min.js"),
);

// One icon per module instead of one chunk holding every icon the app uses
const iconRoot = path.resolve(require.resolve("react-icons"), "..");
const scriptPath = (name) =>
  fileURLToPath(new URL(`./scripts/${name}`, import.meta.url));
const iconStub = scriptPath("icon-stub.js");

const pwaDisabled =
  process.env.NODE_ENV === "development" ||
  process.env.NEXT_DISABLE_PWA === "1";

// A service worker was shipped until 2026-08-29. While the PWA build is off,
// publish a worker whose only job is to delete those caches and unregister.
if (pwaDisabled) {
  writeFileSync(
    fileURLToPath(new URL("./public/sw.js", import.meta.url)),
    `// Retired service worker: removes its caches and unregisters itself.
self.addEventListener("install", () => self.skipWaiting());
self.addEventListener("activate", (event) => {
  event.waitUntil(
    (async () => {
      for (const key of await caches.keys()) await caches.delete(key);
      await self.registration.unregister();
    })(),
  );
});
`,
  );
}

const withPWA = withPWAInit({
  dest: "public",
  extendDefaultRuntimeCaching: true,
  publicExcludes: ["!noprecache/**/*", "!connection-check.txt"],
  workboxOptions: {
    runtimeCaching: [
      { urlPattern: ({ url }) => url.pathname === "/connection-check.txt", handler: "NetworkOnly", method: "GET" },
      // Bearer-link pages and their RSC responses must never enter Cache Storage.
      { urlPattern: PRIVATE_PAGE_URL, handler: "NetworkOnly", method: "GET" },
      // API data is live; never serve it from the SW cache.
      { urlPattern: ({ url }) => url.pathname.startsWith("/api/"), handler: "NetworkOnly", method: "GET" },
    ],
  },
  cacheOnFrontEndNav: false,
  reloadOnOnline: false,
  disable: pwaDisabled,
});

const withNextIntl = createNextIntlPlugin("./src/i18n/request.ts");

// Routes switched off by prefixing their folder with "_". Temporary (307) redirects.
const LOCALE_PREFIX = "/:locale(en|de|es|ar|zh)";
const DISABLED_ROUTE_REDIRECTS = [
  ["/signin", "/auth/sign-in"],
  ["/access_denied", "/access-denied"],
  ["/members/new_member/v2", "/members/new_member"],
  ["/members/new_member/v3", "/members/new_member"],
  ["/booking", "/dashboard"],
  ["/file", "/dashboard"],
  ["/gallery", "/dashboard"],
  ["/sms", "/dashboard"],
].flatMap(([from, to]) => [
  { source: from, destination: to, permanent: false },
  { source: `${LOCALE_PREFIX}${from}`, destination: `/:locale${to}`, permanent: false },
]);

/** @type {import('next').NextConfig} */
const nextConfig = {
  distDir: process.env.NEXT_LOCAL_PREVIEW === "1" ? ".next-local-preview"
    : process.env.NEXT_PAYMENT_PREVIEW === "1" ? ".next-payment-preview" : ".next",
  output: process.env.DOCKER_BUILD === "1" ? "standalone" : undefined,
  reactStrictMode: true,
  compiler: {
    removeConsole: process.env.NODE_ENV === "production" ? { exclude: ["error", "warn"] } : false,
  },
  productionBrowserSourceMaps: false,
  cacheComponents: false,
  typescript: { ignoreBuildErrors: true },
  env: {
    NEXT_PUBLIC_GOOGLE_MAP_API_KEY: process.env.NEXT_PUBLIC_GOOGLE_MAP_API_KEY,
    NEXTAUTH_URL: process.env.NEXTAUTH_URL,
    NEXT_PUBLIC_API_URL: process.env.NEXT_PUBLIC_API_URL || "https://apiv2.gymforce.in",
    NEXT_PUBLIC_URL: process.env.NEXT_PUBLIC_URL || process.env.NEXT_PUBLIC_API_URL || "https://apiv2.gymforce.in",
    NEXT_PUBLIC_GOOGLE_CLIENT_ID: process.env.NEXT_PUBLIC_GOOGLE_CLIENT_ID,
    NEXT_PUBLIC_ENCRYPTION_KEY: process.env.NEXT_PUBLIC_ENCRYPTION_KEY,
    NEXT_PUBLIC_GA_ID: process.env.NEXT_PUBLIC_GA_ID,
    NEXT_PUBLIC_POSTHOG_KEY: process.env.NEXT_PUBLIC_POSTHOG_KEY,
    NEXT_PUBLIC_POSTHOG_HOST: process.env.NEXT_PUBLIC_POSTHOG_HOST,
    NEXT_PUBLIC_ACTIVITY_LOG_ENABLED: process.env.NEXT_PUBLIC_ACTIVITY_LOG_ENABLED || "true",
    NEXT_PUBLIC_SENTRY_DSN: process.env.NEXT_PUBLIC_SENTRY_DSN || "<GlitchTip DSN – redacted>",
  },
  images: {
    unoptimized: true,
    formats: ["image/avif", "image/webp"],
    remotePatterns: [
      { protocol: "https", hostname: "randomuser.me", pathname: "/api/portraits/**" },
      { protocol: "https", hostname: "cloudflare-ipfs.com", pathname: "/ipfs/**" },
      { protocol: "https", hostname: "avatars.githubusercontent.com", pathname: "/u/**" },
      { protocol: "https", hostname: "picsum.photos" },
      { protocol: "https", hostname: "flagcdn.com" },
      { protocol: "https", hostname: "utfs.io" },
      { protocol: "https", hostname: "images.unsplash.com" },
      { protocol: "https", hostname: "buildupfitness.in" },
      { protocol: "https", hostname: "s3.amazonaws.com", pathname: "/redqteam.com/isomorphic-furyroad/public/**" },
      { protocol: "https", hostname: "isomorphic-furyroad.s3.amazonaws.com" },
      { protocol: "https", hostname: "isomorphic-furyroad.vercel.app" },
      { protocol: "https", hostname: "images.gymforce.in" },
      { protocol: "https", hostname: "media.gymforce.in" },
      { protocol: "https", hostname: "files.gymforce.in" },
      { protocol: "https", hostname: "firebasestorage.googleapis.com", pathname: "/**" },
    ],
  },
  transpilePackages: ["core"],
  experimental: {
    // Page shells carry no data, so a shell visited in the last 5 minutes is reused.
    staleTimes: { dynamic: 300, static: 300 },
  },
  webpack(config, { isServer }) {
    if (process.env.NEXT_LOCAL_PREVIEW === "1" && process.env.NODE_ENV === "production") {
      config.cache = false;
    }
    if (!isServer) config.output.chunkLoadTimeout = 20_000;
    config.resolve.alias["gf-icon$"] = iconStub;
    config.module.rules.push(
      {
        resource: iconStub,
        resourceQuery: /family=/,
        enforce: "pre",
        loader: scriptPath("icon-loader.cjs"),
        options: { root: iconRoot },
      },
      {
        test: /__barrel_optimize__/,
        enforce: "post",
        use: ({ resourceQuery }) => {
          const names = /wildcard/.test(resourceQuery)
            ? []
            : (resourceQuery.match(/\?names=([^&]+)/)?.[1] || "").split(",");
          return [{
            loader: scriptPath("icon-barrel-loader.cjs"),
            options: { root: iconRoot, names: names.filter(Boolean) },
            ident: `gf-icon-barrel:${resourceQuery}`,
          }];
        },
      },
    );
    config.resolve.alias["tailwind-merge$"] = path.resolve(require.resolve("tailwind-merge"), "../..");
    return config;
  },
  async headers() {
    const staticAssetCache = [
      "/favicon.ico", "/favicon-:size.png",
      "/icon.png", "/icons/:path*", "/newlogo/:path*",
    ].map((source) => ({ source, headers: [
      { key: "Cache-Control", value: "public, max-age=86400, stale-while-revalidate=604800" },
    ] }));
    return [...staticAssetCache, ...["/pay/:path*", "/onboarding/:path*",
      "/oauth/authorize", "/auth/sign-in",
      `${LOCALE_PREFIX}/oauth/authorize`, `${LOCALE_PREFIX}/auth/sign-in`,
      `${LOCALE_PREFIX}/pay/:path*`, `${LOCALE_PREFIX}/onboarding/:path*`]
      .map((source) => ({ source, headers: [
        ...PRIVATE_LINK_HEADERS,
        ...(source.includes("oauth/authorize") ? [
          { key: "X-Frame-Options", value: "DENY" },
          { key: "Content-Security-Policy", value: "frame-ancestors 'none'; base-uri 'self'" },
        ] : []),
      ] }))];
  },
  async redirects() {
    return DISABLED_ROUTE_REDIRECTS;
  },
};

const sentryWebpackPluginOptions = {
  silent: true,
  org: process.env.SENTRY_ORG || "gymforce",
  project: process.env.SENTRY_PROJECT || "gymforcev5",
  sentryUrl: process.env.SENTRY_URL || "<GlitchTip URL – redacted>",
  authToken: process.env.SENTRY_AUTH_TOKEN,
};

const sentryOptions = {
  widenClientFileUpload: false,
  transpileClientSDK: false,
  hideSourceMaps: true,
  disableLogger: true,
  automaticVercelMonitors: false,
  disableClientWebpackPlugin: true,
  disableServerWebpackPlugin: true,
};

const baseConfig = withNextIntl(withPWA(nextConfig));

export default process.env.SENTRY_AUTH_TOKEN &&
process.env.SENTRY_UPLOAD_SOURCE_MAPS === "true"
  ? withSentryConfig(baseConfig, sentryWebpackPluginOptions, sentryOptions)
  : baseConfig;
Editor is loading...
Leave a Comment