VENNStart
Guide

Sharing web and mobile code with Next.js, Capacitor and Turborepo

Two Next.js apps in one monorepo: server rendering for the web, static export for Capacitor. What we could share and where I got stuck.

Lê Anh Tuấn4 min read

One team had to put this SaaS product on web, iOS and Android. The React UI and API calls already existed, so the mobile app is Next.js too, a static export wrapped in Capacitor, while the web app keeps server rendering. Both are in one pnpm workspace run by Turborepo.

Two apps, one set of shared packages

  • apps/next-web, the server-rendered Next.js app, built into a Docker image
  • apps/next-app, Next.js with output: 'export', plus the ios/ and android/ projects Capacitor generates
  • packages/ui, lib, services, store, types, and shared config and tsconfig
  • packages/app, with no code, only the shared versions of next, react, react-hook-form, zod and friends

packages/app is my favorite part. Both apps depend on app: "workspace:*", so upgrading Next.js from 15.2.8 to 15.5.9 was one line, pinned so both apps run the same release.

.npmrc sets node-linker=hoisted because Gradle and CocoaPods resolve Capacitor plugins through paths into node_modules, and I didn't want to find out which native tool trips over symlinks. A package can then import a dependency it never declared. I'm fine with that.

Static export drops everything that needs a server

With output: 'export', Next.js drops middleware (proxy since 16, this repo is on 15.5), cookies(), Server Actions, rewrites, redirects and headers from next.config, ISR, draft mode, intercepting routes, request-dependent Route Handlers, default image optimization, and dynamic routes without generateStaticParams or with dynamicParams: true.

The web version relies on middleware, cookies, redirects and security headers. The native app has its own config and builds to out/, which Capacitor copies into the native projects:

// apps/next-app/next.config.ts
import type { NextConfig } from 'next';
import path from 'path';

const nextConfig: NextConfig = {
  output: 'export',
  trailingSlash: true, // emits /settings/index.html instead of /settings.html
  images: { unoptimized: true }, // no image server inside the app
  transpilePackages: ['ui', 'lib', '@ionic/react', '@ionic/react-router', '@ionic/core', 'ionicons'],
  experimental: {
    // @ionic/core ships ESM that Node chokes on during the build otherwise
    esmExternals: 'loose',
  },
  outputFileTracingRoot: path.join(__dirname, '../../'),
};

export default nextConfig;

Next.js only builds a client-side shell, where Ionic React's IonReactRouter handles tabs, transitions and the back stack, so mobile navigation doesn't depend on App Router.

// app/(mobile)/[...all]/page.tsx
import ClientPage from './mobile'; // 'use client' + dynamic(() => import('./router'), { ssr: false })
import { ALL_ROUTES } from '@/config/routes';

export async function generateStaticParams() {
  // '/app/items/:id' -> ['app', 'items']; the router reads the id on the client
  return ALL_ROUTES.map(({ path }) => ({
    all: path
      .replace(/\/:[^/]+/g, '')
      .split('/')
      .filter(Boolean),
  }));
}

export default function Page() {
  return <ClientPage />;
}

Each route in the router config gets an HTML shell with dynamic segments stripped, and react-router reads the real :id at runtime.

Shared packages with no build step

Each package points main at its source index.ts or index.tsx, and Next compiles that source directly (ui and lib are listed in transpilePackages). Edit a component in packages/ui and both apps hot-reload.

Importing @capacitor/core on the web is safe, since Capacitor.isNativePlatform() returns false in a browser. lib can then branch per platform. A download opens the URL on the web and writes to Documents in the app.

// packages/lib/feat/download.ts
import { Capacitor } from '@capacitor/core';
import { Directory, Filesystem } from '@capacitor/filesystem';

const blobToBase64 = (blob: Blob) =>
  new Promise<string>((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = () => resolve(String(reader.result).split(',')[1]);
    reader.onerror = reject;
    reader.readAsDataURL(blob);
  });

export async function downloadFile(url: string, filename: string) {
  if (!Capacitor.isNativePlatform()) {
    window.open(url, '_blank', 'noopener,noreferrer');
    return;
  }

  const res = await fetch(url);
  if (!res.ok) throw new Error(`Download failed: ${res.status}`);

  const { uri } = await Filesystem.writeFile({
    path: filename,
    data: await blobToBase64(await res.blob()), // binary has to go in as base64
    directory: Directory.Documents,
    recursive: true,
  });
  return uri;
}

On iOS, files in Documents don't show up in the Files app until Info.plist sets UIFileSharingEnabled and LSSupportsOpeningDocumentsInPlace.

Local storage moved from @ionic/storage to a wrapper around @capacitor/preferences, cutting about 4,000 lockfile lines. Preferences suits settings and small caches. Queryable data belongs in SQLite.

Turborepo has to cache out/ too

The turbo.json is short:

{
  "tasks": {
    "build": {
      "dependsOn": ["^build"],
      "outputs": ["dist/**", ".next/**", "!.next/cache/**", "out/**"]
    },
    "lint": { "outputs": [] },
    "test": { "dependsOn": ["^build"], "outputs": ["coverage/**"] },
    "dev": { "cache": false, "persistent": true }
  },
  "globalEnv": ["NODE_ENV", "NEXT_PUBLIC_API_URL", "NEXT_PUBLIC_APP_STAGE"]
}

Watch outputs. The real repo lists only dist/** and .next/** while the export app writes to out/, and on a cache hit Turborepo can't restore the folder Capacitor needs. I added out/** above. The real repo still lacks it, and I can't say whether that ever broke a build.

In Turborepo 2's strict mode, only variables listed in env or globalEnv reach the task and change the hash. NEXT_PUBLIC_* is inferred, but .env files aren't hashed unless they're in inputs. If an env file changes without changing the task hash, Turborepo can restore a build with the old values.

Capacitor sync, live reload, plugins and push

On iOS, cap sync failed in Xcode's clean step because nanopb (pulled in by Firebase) left a build folder in DerivedData. sync-ios-safe.sh deletes them, runs cap copy ios, cap update ios and pod install, and lets cap update ios continue on errors. I don't want it around long, because real failures pass too.

Live reload needs server.url pointing at the dev server on your LAN, with cleartext: true. The repo toggles it by commenting config lines, and server.url isn't for production. I'd use an env var so a dev URL doesn't need a source edit:

// apps/next-app/capacitor.config.ts
import type { CapacitorConfig } from '@capacitor/cli';

// CAP_SERVER_URL=http://<your-lan-ip>:3000 npx cap run ios
const liveReloadUrl = process.env.CAP_SERVER_URL;

const config: CapacitorConfig = {
  appId: 'com.example.app',
  appName: 'Example',
  webDir: 'out',
  server: liveReloadUrl
    ? { url: liveReloadUrl, cleartext: true }
    : { androidScheme: 'https' },
  plugins: {
    PushNotifications: { presentationOptions: ['badge', 'sound', 'alert'] },
  },
};

export default config;

For cross-origin errors on /_next resources, add your LAN IP to allowedDevOrigins.

Git tracks 248 synced asset files under android/app/src/main/assets/public. Gitignore them.

Plugin major versions should match @capacitor/core. We're on 7, yet the lockfile has @capacitor/browser 8.0.0 next to core 7.4.4, because a dependency update bumped it back after I'd downgraded it. I haven't retested on a device.

Push took the most attempts. The first version called unregister(), waited, called register() and slept two seconds to make registration fire. Don't copy that. On iOS the registration token is an APNs token, while the backend sends through FCM. With @capacitor-community/fcm, matching AppDelegate changes and FCM.getToken() right after register(), both platforms get an FCM token. Attach the registrationError, foreground and tap listeners before register().

Auth and env vars per platform

On the web, middleware reads the session cookie before rendering (Next.js auth cookies and local dev). The native app has no server. The axios instance in lib checks the platform in an interceptor and sends the token as an Authorization header.

Route guards in the app run on the client, which only helps UX. The API enforces roles and plan limits itself, as in RBAC and subscription gating. Tokens on the device belong in Keychain/Keystore-backed secure storage, not Preferences.

NEXT_PUBLIC_* values are inlined at build time, and a store build can't change them until the next release. Build once per environment and don't detect it at runtime. Reading the environment from window.location.hostname can't work in the app, where the WebView hostname comes from the Capacitor config, so our helper falls back to the API URL set at build time.

I'd pick this setup again when web and mobile share a lot of React UI and logic, because the design system, API layer and types exist once. If the mobile app needs much of what static export drops, go another way. This repo also never tried Capacitor with pnpm's symlinked layout.

  • Next.js
  • Capacitor
  • Turborepo
  • pnpm
  • Monorepo
  • Mobile

I'm Tuấn (Venn), a web developer in Ho Chi Minh City. I mostly build Next.js sites and web apps, and I take freelance work.

Work with me

More posts

  1. 01Guide4 min read

    Deploying Next.js and NestJS to AWS EC2 with Docker Compose

    How I deploy a pnpm monorepo to one EC2 box. Images get built in GitHub Actions and Docker Compose pulls them from GHCR. The server has no code.

  2. 02Guide4 min read

    How I store OAuth tokens for social media APIs in NestJS

    OAuth for Facebook, TikTok and YouTube in a NestJS API. State and PKCE, encrypted tokens, refreshing before each publish, and when to ask for a reconnect.

  3. 03vennee.dev3 min read

    llms.txt on my Next.js site, and now Lighthouse grades it

    vennee.dev has a hand-written llms.txt and an llms-full.txt built from the blog. Notes on the spec, .txt routes in Next.js, and Lighthouse 13's new audit.