Next.js Discord

Discord Forum

problem with using CommonJS require only when I use import in`middleware.ts`

Answered
Yaman posted this in #help-forum
Open in Discord
I have my axios setup and I used CommonJS to do it my axios/index.js file:
const Axios = require(“axios”);
const process = require(“process”);
const instance = Axios.create({
  baseURL: “https://api.msaaq.test/v1/tenant”,
  withCredentials: false,
  headers: {
    Accept: “application/json”,
    “X-Requested-With”: “XMLHttpRequest”
  }
});
const setTenantDomain = (req) => {
  if (process.env.NEXT_PUBLIC_APP_URL) {
    instance.defaults.headers.common[“X-Academy-Domain”] = process.env.NEXT_PUBLIC_APP_URL;
    return;
  }
  if (typeof req === “string”) {
    instance.defaults.headers.common[“X-Academy-Domain”] = req;
    return;
  }
  if (typeof req === “object” && req.headers && req.headers.host) {
    instance.defaults.headers.common[“X-Academy-Domain”] = req.headers.host;
    return;
  }
  throw new Error(“Invalid request parameter”);
};
const setAuthToken = (token) => {
  if (token) {
    instance.defaults.headers.common[“Authorization”] = `Bearer ${token}`;
  } else {
    delete instance.defaults.headers.common[“Authorization”];
  }
};
const setCurrentAcademyId = (academyId) => {
  if (academyId) {
    instance.defaults.headers.common[“X-Academy-ID”] = academyId;
  } else {
    delete instance.defaults.headers.common[“X-Academy-ID”];
  }
};
module.exports = {
  instance,
  setTenantDomain,
  setAuthToken,
  setCurrentAcademyId
};

and when I use setAuthToken from my middleware.ts file like this:
import { setAuthToken } from “@/lib/axios”;
 setAuthToken(token.access_token);

I get this error:
- error lib/axios/index.js (4:0) @ <unknown>
- error Axios.create is not a function
but when remvoe the usage of setAuthToken from the middleware file everything works fine and even I tried to conole.log(Axios.create) I get the correct value
any idea what is worng here?
Answered by Yaman
I am not using axios in the middleware.ts to fetch data, im just creating the instance and set the auth token

but I am using axios in next-i18next.config.js and it does not accept it when using
import Axios from "axios";

for now when I changed it to:
const Axios = require("axios").default;
it worked in fine my local env
I will deploy it to dev and prod to see what might happen
and I will post update here as well
thanks a lot for the answers @tafutada777 🙏🏻
View full answer

5 Replies

@Yaman require is not supported by Edge Runtime, where middleware is supposed to be run.
https://vercel.com/docs/concepts/functions/edge-functions/edge-runtime#unsupported-apis
@tafutada777 <@428500222709071892> require is not supported by Edge Runtime, where middleware is supposed to be run. https://vercel.com/docs/concepts/functions/edge-functions/edge-runtime#unsupported-apis
@tafutada777 thanks for pointing out to this, I had not idea about it.
but I have to use require in my file because I am using axios in next-i18next.config.js
if I use import it will not work,

here is how I am using axios in my i18next.config
const backend = require("i18next-http-backend/cjs");
const { axios } = require("./lib/axios");

module.exports = {
  debug: false,
  i18n: {
    locales: ["ar"],
    defaultLocale: "ar"
  },
  use: [backend],
  backend: {
    loadPath: "{{lng}}|{{ns}}",
    request: async (options, url, payload, callback) => {
      try {
        const [lng, ns] = url.split("|");

        await axios
          .get("/translations", {
            params: { group: ns }
          })
          .then((response) => {
            callback(null, {
              data: response.data.data[lng][ns],
              status: 200
            });
          })
          .catch((error) => {
            console.log(error.response);
          });
      } catch (e) {
        callback(null, {
          status: 500
        });
      }
    }
  },
  serializeConfig: false
};


when I try to use import I get this error:
import Axios from "axios";
^^^^^^

SyntaxError: Cannot use import statement outside a module

BUT when I used require like this:
const Axios = require("axios").default;

it worked fine without any issues

do you anyidea on how I can solve it using import?
i am not 100% sure but axios does not work with middleware.ts
Edge Runtime, where middleware.ts deployed, is not Node.js. its a kinda light version Node.js, which support subset of Node.js
i found a similar issue at
https://www.reddit.com/r/nextjs/comments/tx1pcp/using_axios_in_middleware_not_working/
a workaround could be, move the logic to API(AWS lambda), then use fetch to invoke it from middleware.ts
I am not using axios in the middleware.ts to fetch data, im just creating the instance and set the auth token

but I am using axios in next-i18next.config.js and it does not accept it when using
import Axios from "axios";

for now when I changed it to:
const Axios = require("axios").default;
it worked in fine my local env
I will deploy it to dev and prod to see what might happen
and I will post update here as well
thanks a lot for the answers @tafutada777 🙏🏻
Answer