diff --git a/.changeset/friendly-cameras-trade.md b/.changeset/friendly-cameras-trade.md new file mode 100644 index 0000000000..0917401440 --- /dev/null +++ b/.changeset/friendly-cameras-trade.md @@ -0,0 +1,5 @@ +--- +'@aws-amplify/backend': patch +--- + +add check to `@aws-amplify/backend` entrypoint to throw early in a browser context diff --git a/packages/backend/src/index.ts b/packages/backend/src/index.ts index 039b5de54c..46adc6515e 100644 --- a/packages/backend/src/index.ts +++ b/packages/backend/src/index.ts @@ -1,3 +1,11 @@ +import { isBrowser } from './is_browser.js'; + +if (isBrowser()) { + throw new Error( + 'This package is for backend use only and should not be used in a browser environment.' + ); +} + export { defineBackend } from './backend_factory.js'; export * from './backend.js'; export * from './secret.js'; diff --git a/packages/backend/src/is_browser.test.ts b/packages/backend/src/is_browser.test.ts new file mode 100644 index 0000000000..cbe64c99bc --- /dev/null +++ b/packages/backend/src/is_browser.test.ts @@ -0,0 +1,25 @@ +import { equal } from 'node:assert/strict'; +import { afterEach, describe, it } from 'node:test'; +import { isBrowser } from './is_browser.js'; + +void describe('is browser', () => { + void afterEach(() => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + delete (global as any).window; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + delete (global as any).document; + }); + + void it('should be true in a browser context', () => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + (global as any).window = {}; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + (global as any).document = {}; + + equal(isBrowser(), true); + }); + + void it('should be false in a node context', () => { + equal(isBrowser(), false); + }); +}); diff --git a/packages/backend/src/is_browser.ts b/packages/backend/src/is_browser.ts new file mode 100644 index 0000000000..4224ee1b4f --- /dev/null +++ b/packages/backend/src/is_browser.ts @@ -0,0 +1,7 @@ +/** + * Checks whether we are in a browser + */ +export const isBrowser = () => { + // @ts-expect-error we're checking for browser context and globalThis does not have an index signature + return typeof globalThis.window !== 'undefined'; +};