Skip to content

Importing bundled library in Node.js throws ReferenceError: self is not defined #473

@mattlubner

Description

@mattlubner

Expected Behavior

Importing amplitude-js within a Next.js project should not throw errors.

Current Behavior

ReferenceError: self is not defined is thrown whenever the Next.js server renders a page. This happens in both the dev server and when building or exporting the site.

Possible Solution

Use the standards-compliant globalThis instead of the ad hoc GlobalScope definition.

Steps to Reproduce

  1. Create a new Next.js project with TypeScript: yarn create next-app --typescript
  2. Add Amplitude to the project's dependencies: yarn add amplitude-js @types/amplitude-js
  3. Import Amplitude in pages/index.tsx: import amplitude from 'amplitude-js';
  4. Very Important! Reference the imported amplitude library to force its inclusion in the JS bundle:
    // pages/index.tsx
    // ...
    import amplitude from 'amplitude-js';
    
    if (false) {
      // never executed, but needed to trigger the ReferenceError
      amplitude.getInstance().init('testing');
    }
    
    const Home: NextPage = () => {
    // ...
  5. Start the dev server: yarn dev
  6. Trigger a page render by loading the app in a browser: http://localhost:3000
  7. See the ReferenceError: self is not defined error being caused by this line in amplitude-js:
    var GlobalScope = typeof window !== 'undefined' ? window : self;

Environment

  • JS SDK Version: 8.14.0
  • Installation Method: Yarn v3.1.1
  • Browser and Version: (not a browser error)
  • Server and Version: Next.js v11.1.3 through v12.0.7, tested on both Node.js v14.18.2 and v17.2.0

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions