Upon setting up 'next-auth@beta' on the server, I encountered the [ERR_REQUIRE_ESM] Error

I have successfully integrated Next Auth into a Next Js application, which utilizes apollo client and apollo server with graphql. I have set up OAuth with Google using Next Auth v5 that supports App Router. On the frontend, I am able to handle sign-in, sign-out, and manage sessions. However, when attempting to retrieve the session on the server using express middleware in my apollo express server, I encountered an error after installing 'next-auth@beta':

C:\Users\hamzz\AppData\Roaming\npm\node_modules\ts-node\dist\index.js:851
            return old(m, filename);
                   ^
Error [ERR_REQUIRE_ESM]: require() of ES Module C:\Hamza the Developer\ChatApp\next-chat\server\node_modules\next-auth\react.js from C:\Hamza the Developer\ChatApp\next-chat\server\api\index.ts not supported.
Instead change the require of react.js in C:\Hamza the Developer\ChatApp\next-chat\server\api\index.ts to a dynamic import() which is available in all CommonJS modules.
    at require.extensions.<computed> [as .js] (C:\Users\hamzz\AppData\Roaming\npm\node_modules\ts-node\dist\index.js:851:20)
    at Object.<anonymous> (C:\Hamza the Developer\ChatApp\next-chat\server\api\index.ts:46:17)
    at m._compile (C:\Users\hamzz\AppData\Roaming\npm\node_modules\ts-node\dist\index.js:857:29) {     
  code: 'ERR_REQUIRE_ESM'
}

[nodemon] app crashed - waiting for file changes before starting...

My goal is to access the session on the server using express middleware and getSession() from next-auth@beta.

app.use(
"/api/graphql",
//@ts-ignore
cors<cors.CorsRequest>(corsOptions),
json(),
expressMiddleware(server, {
  context: async ({ req }): Promise<IContext> => {
    if (!req.headers.cookie) {
      return { session: null, prisma, pubsub };
    }
    const session = await getSession();

    return {
      session: session as Session,
      pubsub,
      prisma,
    };
  },
})

);

Answer №1

The issue you're facing arises from the incompatible module types between next-auth/react (ES module) and ts-node package (CommonJS module).

To resolve this, switch from using the require() function for importing next-auth/react to utilizing dynamic imports that are compatible with CommonJS modules.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating a file logging system with log4js to capture Console logs

Is there a way to automatically log all console logs, including failed expectations and exceptions, to a file without using try and catch in JavaScript? In Java's LOG4j, the rootlogger feature does this by default. Is there a similar functionality ava ...

Tips for ensuring that eslint typescript identifies interfaces in .d.ts files

Currently, I am working on a project that involves Vite 3, Vuetify 3, and Vue 3 with the Volar extension. I have defined interfaces in some .d.ts files and also have ESLint installed. However, ESLint keeps complaining about not being able to find the inter ...

What causes TypeScript to interpret an API call as a module and impact CSS? Encountering a Next.js compilation error

My website development process hit a roadblock when I tried integrating Material Tailwind into my project alongside Next.js, Typescript, and Tailwind CSS. The compilation error that popped up seemed unrelated to the changes, leaving me baffled as to what c ...

Using curly brackets as function parameters

Can someone help me understand how to pass an emailID as a second parameter in curly braces as a function parameter and then access it in AccountMenuSidebar? I apologize for asking such a basic question, I am new to JavaScript and React. class Invoices ex ...

Javascript's callback mechanism allows functions to be passed as arguments

I am currently delving into the intricacies of the callback mechanism in javascript, particularly typescript. If I have a function that expects a callback as an input argument, do I need to explicitly use a return statement to connect it with the actual ca ...

In what ways can elements of the general concept be inferred from incorporating TypeScript?

I'm facing a challenge in figuring out how to achieve a specific task. We have a function called createActions that requires an object type and a string as a key. function createActions<T, Tkey extends string>(key: Tkey) { return function(o ...

Utilizing external imports in webpack (dynamic importing at runtime)

This is a unique thought that crossed my mind today, and after not finding much information on it, I decided to share some unusual cases and how I personally resolved them. If you have a better solution, please feel free to comment, but in the meantime, th ...

Is there a way to modify a particular row in a table with Angular 5?

I am facing an issue with a table in my component that contains multiple records. Whenever I try to edit a specific row by clicking the edit button, it ends up making all rows editable instead. Here is how my table looks: The problem lies in the fact tha ...

I'm encountering difficulty accessing the Index value within the template's Ref

I'm having trouble accessing the index value inside the templateRef. It shows as undefined in the console. <ng-container *ngFor="let notification of notifications; let i = index"> <ng-template *ngTemplateOutlet="notificationPage ...

The Vue event was triggered, however there was no response

My current project consists of a Typescript + Vue application with one parent object and one component, which is the pager: //pager.ts @Component({ name: "pager", template: require("text!./pager.html") }) export default class Pager extends Vue { ...

Issue with Codemirror lint functionality not functioning properly in a React/Redux/Typescript application

I'm currently working on enabling the linting addon for the react-codemirror package in a React/Redux/TS application. The basic codemirror features like syntax highlighting and line numbers are functioning properly. However, upon enabling linting, I n ...

Is it possible to add additional text to an input field without modifying its existing value?

I have a numerical input field labeled "days" that I want to add the text " days" to without altering the actual numerical value displayed. <input type="number" class="days" (keyup)="valueChanged($event)"/> Users should only be able to edit the num ...

Delay the execution of a JavaScript method that resolves a promise

Currently, I am delving into the world of Angular 2, typescript, promises, and more. I've set up a small application for developer tools with a service that simply returns hard-coded data. This setup is purely for testing purposes. I want to introduc ...

Utilizing data retrieval caching in nextjs getServerSideProps() for optimized performance

I am currently developing an application using nextjs that retrieves data from a firebase firestore. The issue I am facing is that the application makes these requests on every page load, even when the data does not need to be completely up to date. To add ...

What is preventing me from being able to spyOn() specific functions within an injected service?

Currently, I am in the process of testing a component that involves calling multiple services. To simulate fake function calls, I have been injecting services and utilizing spyOn(). However, I encountered an issue where calling a specific function on one ...

Issue with ngx-extended-pdf-viewer when using URL

I'm struggling to display my PDF file on a viewer using a URL in TypeScript. I am utilizing ngx-extended-pdf-viewer. Below is a snippet of my code with the URL replaced: <ngx-extended-pdf-viewer *ngIf="!isFirefox" [src]="'http://www.chi ...

What is the best way to make the NextJS Image Component in React JSX automatically adjust its height?

I need to maintain the aspect ratio while keeping the width fixed. Can you assist me in automatically adjusting the height? I prefer to stick with using the Nextjs Image component if feasible. const Logo = ({ logo }) => { if (logo) { return ( ...

The local types package cannot be built by react-scripts even though tsc has successfully completed the process

I have developed an application with a TypeScript frontend and backend. To streamline the process, I decided to create a shared types module that contains all the necessary types for both components in one centralized location. Rather than going through th ...

Issues with NextJS symlinks failing to update and causing crashes in a Kubernetes deployment are causing disruptions in

Welcome My Kubernetes deployment includes a NextJS app that I want to run in development mode for instant hot-reloading when files are updated. Specifically, I am focusing on updating JSON files within the "config" folder. To achieve this, I have set up a ...

In Javascript, check if an item exists by comparing it to null

I am working with a dropdown list that can be used for various types of data. Some of the data includes an isActive flag (a BOOLEAN) while others do not. When the flag is absent, I would like to display the dropdown item in black. However, if the flag exis ...