user18107098
user18107098

Reputation:

Next.js v12 middleware does not work with node-fetch and axios

I am currently trying to create a middleware that will user's data by fetching an external endpoint with Axios. Axios too, does not work with the middleware. Here is my error when using node-fetch:

Module build failed: UnhandledSchemeError: Reading from "node:buffer" is not handled by plugins (Unhandled scheme).
Webpack supports "data:" and "file:" URIs by default.
You may need an additional plugin to handle "node:" URIs.

Any idea why this happens?

Here is my code:

import fetch from "node-fetch"
import { getSession } from "next-auth/react";
import { NextMiddleware, NextResponse } from "next/server";

export const middleware: NextMiddleware = async (req, ev) => {
  const session = await getSession() as any;
  const user = await fetch("some-url", {
    headers: {
      Authorization: `Bearer ${session?.user?.someproperty}`,
    },
  });

  if (user.statusCode !== 200) return NextResponse.redirect(req.url);
  else return NextResponse.next();
};

Upvotes: 11

Views: 10787

Answers (2)

Jeremy
Jeremy

Reputation: 89

Since node v18, already built-in fetch, I create a lib similar API to axios and use fetch, lightweight, and many built-in plugins support.

And many people already use this lib(10k download per month), and very stable, check now: https://www.npmjs.com/package/xior

Upvotes: 0

Saul Montilla
Saul Montilla

Reputation: 804

In my case I was using axios inside middleware, and got the following error

error - node_modules\axios\lib\core\dispatchRequest.js (53:0) @ dispatchRequest
TypeError: adapter is not a function

I had to install axios-fetch-adapter according to this question

My code would like

import type { NextFetchEvent, NextRequest } from 'next/server'
import fetchAdapter from '@vespaiach/axios-fetch-adapter'
import axios from 'axios'

export async function middleware(req: NextRequest, ev: NextFetchEvent) {
    const axiosInstance = axios.create({
        adapter: fetchAdapter
    })

    const data = await axiosInstance.get('/whatever-url')

    // the rest of the code

}

Or if you already had a preconfigured instance with custom options

import type { NextFetchEvent, NextRequest } from 'next/server'
import fetchAdapter from '@vespaiach/axios-fetch-adapter'
import axiosInstance from './the-path-of-your-instance'

export async function middleware(req: NextRequest, ev: NextFetchEvent) {
    axiosInstance.defaults.adapter = fetchAdapter

    const data = await axiosInstance.get('/whatever-url')

    // the rest of the code

}

Upvotes: 6

Related Questions