Skip to content

Commit 882cd7c

Browse files
authored
Merge pull request #1053 from objectstack-ai/copilot/fix-msw-service-worker-path
2 parents 0a088aa + c443a10 commit 882cd7c

File tree

1 file changed

+23
-6
lines changed

1 file changed

+23
-6
lines changed

apps/console/src/mocks/browser.ts

Lines changed: 23 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
*/
1111

1212
import { http, HttpResponse } from 'msw';
13+
import { setupWorker } from 'msw/browser';
1314
import { ObjectKernel } from '@objectstack/runtime';
1415
import { InMemoryDriver } from '@objectstack/driver-memory';
1516
import type { MSWPlugin } from '@objectstack/plugin-msw';
@@ -20,6 +21,7 @@ import { createAuthHandlers } from './authHandlers';
2021
let kernel: ObjectKernel | null = null;
2122
let driver: InMemoryDriver | null = null;
2223
let mswPlugin: MSWPlugin | null = null;
24+
let worker: ReturnType<typeof setupWorker> | null = null;
2325

2426
/**
2527
* Load application-specific locale bundles for the i18n API endpoint.
@@ -57,7 +59,7 @@ export async function startMockServer() {
5759
const result = await createKernel({
5860
appConfig,
5961
mswOptions: {
60-
enableBrowser: true,
62+
enableBrowser: false,
6163
baseUrl: '/api/v1',
6264
logRequests: import.meta.env.DEV,
6365
customHandlers: [
@@ -76,18 +78,33 @@ export async function startMockServer() {
7678
driver = result.driver;
7779
mswPlugin = result.mswPlugin ?? null;
7880

81+
// Manually start the MSW browser worker so we can set the service worker
82+
// URL to respect Vite's base path (e.g. '/console/'). Without this, MSW
83+
// defaults to '/mockServiceWorker.js' which 404s when base !== '/'.
84+
const handlers = mswPlugin?.getHandlers() ?? [];
85+
if (handlers.length === 0 && import.meta.env.DEV) {
86+
console.warn('[MSW] No handlers registered — mock API calls will not be intercepted');
87+
}
88+
worker = setupWorker(...handlers);
89+
await worker.start({
90+
serviceWorker: {
91+
url: `${import.meta.env.BASE_URL}mockServiceWorker.js`,
92+
},
93+
onUnhandledRequest: 'bypass',
94+
});
95+
7996
if (import.meta.env.DEV) console.log('[MSW] ObjectStack Runtime ready');
8097
return kernel;
8198
}
8299

83100
export function stopMockServer() {
84-
if (mswPlugin) {
85-
const worker = mswPlugin.getWorker();
86-
if (worker) worker.stop();
87-
mswPlugin = null;
101+
if (worker) {
102+
worker.stop();
103+
worker = null;
88104
}
89-
kernel = null;
105+
mswPlugin = null;
90106
driver = null;
107+
kernel = null;
91108
}
92109

93110
export function getKernel(): ObjectKernel | null {

0 commit comments

Comments
 (0)