Skip to content

Commit

Permalink
Make node-fetch optional (#31)
Browse files Browse the repository at this point in the history
* Make node-fetch optional

* Add info about node-fetch
  • Loading branch information
ofhouse authored Apr 7, 2023
1 parent f092854 commit aebbeec
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 6 deletions.
11 changes: 11 additions & 0 deletions packages/core/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,17 @@ npm i @millihq/pixel-core next react react-dom # squoosh
npm i @millihq/pixel-core next react react-dom sharp # sharp
```

### `fetch` usage

Under the hood, Next.js needs global `fetch` available to request the image from the original source.
The module polyfills it with `node-fetch` if it is not available.

If you are using a Node.js version `< 18` you should also add it as peer dependency:

```sh
npm i node-fetch
```

## Usage

Pixel can be integrated with the standard Node.js HTTP request and response model.
Expand Down
11 changes: 6 additions & 5 deletions packages/core/lib/image-optimizer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ import {
defaultConfig,
NextConfigComplete,
} from 'next/dist/server/config-shared';
import nodeFetch from 'node-fetch';

/* -----------------------------------------------------------------------------
* Types
Expand Down Expand Up @@ -60,10 +59,12 @@ type PixelOptions = {
* ---------------------------------------------------------------------------*/

// Polyfill for fetch that is used by nextImageOptimizer
// https://github.com/vercel/next.js/blob/canary/packages/next/server/image-optimizer.ts#L223

// @ts-ignore
global.fetch = nodeFetch;
// If we are Node.js 18+ where fetch is available we don't need the polyfill.
// https://github.com/vercel/next.js/blob/canary/packages/next/src/server/image-optimizer.ts#L529
if (global.fetch === undefined) {
// @ts-ignore - Our types are still Node.js 14
global.fetch = require('node-fetch');
}

/* -----------------------------------------------------------------------------
* Pixel
Expand Down
2 changes: 1 addition & 1 deletion packages/core/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
"prepack": "cp ../../LICENSE ../../CHANGELOG.md ./",
"postpack": "rm ./LICENSE ./CHANGELOG.md"
},
"dependencies": {
"optionalDependencies": {
"node-fetch": "^2.0.0"
},
"peerDependencies": {
Expand Down

0 comments on commit aebbeec

Please sign in to comment.