Skip to content

Commit

Permalink
add check to @aws-amplify/backend to throw early in a browser conte…
Browse files Browse the repository at this point in the history
…xt (#1810)

* add check to secret() to throw early in a browser context

* "client-side applications" -> "the browser"

* lift "is browser" check to a utility, execute at package entrypoint

* remove stale check from secret()

* update changeset description

* Update packages/backend/src/is_browser.ts

Co-authored-by: Kamil Sobol <[email protected]>

---------

Co-authored-by: Kamil Sobol <[email protected]>
  • Loading branch information
josefaidt and sobolk authored Aug 27, 2024
1 parent 178c518 commit d4c10fe
Show file tree
Hide file tree
Showing 4 changed files with 45 additions and 0 deletions.
5 changes: 5 additions & 0 deletions .changeset/friendly-cameras-trade.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@aws-amplify/backend': patch
---

add check to `@aws-amplify/backend` entrypoint to throw early in a browser context
8 changes: 8 additions & 0 deletions packages/backend/src/index.ts
Original file line number Diff line number Diff line change
@@ -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';
Expand Down
25 changes: 25 additions & 0 deletions packages/backend/src/is_browser.test.ts
Original file line number Diff line number Diff line change
@@ -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);
});
});
7 changes: 7 additions & 0 deletions packages/backend/src/is_browser.ts
Original file line number Diff line number Diff line change
@@ -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';
};

0 comments on commit d4c10fe

Please sign in to comment.