Issue connecting database with error when combining TypeORM with Next.js

I am attempting to use TypeORM with the next.js framework.

Here is my connection setup:

const create =  () => {
    // @ts-ignore
    return createConnection({
        ...config
    });
};
export const getDatabaseConnection = async () => {
    console.log("======getDatabaseConnection====");
    const manager = getConnectionManager();
    const current = manager.has('default') ? manager.get('default'): (await create());
    console.log(current.isConnected)
    await current.connect().catch(e=> console.log(e))
    console.log("======success====");
    console.log(current.isConnected)
    if(current.isConnected){
        console.log("current connected")
    }else{
        await current.connect()
        console.log("current reconnect")
    }
    return current;
};

When checking the console, I receive the following error:

======getDatabaseConnection====
false
/mnt/c/workgit/orm/src/entity/Contact.ts:1
import {Entity, Column, ManyToOne, PrimaryGeneratedColumn} from "typeorm";
^^^^^^

SyntaxError: Cannot use import statement outside a module
    at wrapSafe (internal/modules/cjs/loader.js:1167:16)
    at Module._compile (internal/modules/cjs/loader.js:1215:27)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1272:10)
    at Module.load (internal/modules/cjs/loader.js:1100:32)
    at Function.Module._load (internal/modules/cjs/loader.js:962:14)
    at Module.require (internal/modules/cjs/loader.js:1140:19)
    at require (internal/modules/cjs/helpers.js:75:18)
    at Function.PlatformTools.load (/mnt/c/workgit/orm/node_modules/typeorm/platform/PlatformTools.js:114:28)
    at /mnt/c/workgit/orm/node_modules/typeorm/util/DirectoryExportedClassesLoader.js:39:69
    at Array.map (<anonymous>)
======success====
false

I keep encountering issues when trying to establish a database connection. Even after attempting to connect, the status remains disconnected.

My tsconfig.json configuration is as follows:

{
   "compilerOptions": {
     "emitDecoratorMetadata": true,
     "experimentalDecorators": true,
     "noImplicitAny": true,
     "baseUrl": ".",
     "target": "es5",
     "module": "commonjs",
     "strict": false,
     "esModuleInterop": true,
     "lib": [
       "dom",
       "dom.iterable",
       "esnext"
     ],
     "allowJs": true,
     "skipLibCheck": true,
     "forceConsistentCasingInFileNames": true,
     "noEmit": true,
     "moduleResolution": "node",
     "resolveJsonModule": true,
     "isolatedModules": true,
     "jsx": "preserve"
   },
   "exclude": [
     "node_modules"
   ],
   "include": [
     "next-env.d.ts",
     "**/*.ts",
     "**/*.tsx"
   ]
 }

Unfortunately, simply adding type:"module" in the package.json file results in an error:

 [ERR_REQUIRE_ESM]: Must use import to load ES Module: /mnt/c/workgit/orm/.next/server/pages/api/user/signup.js
require() of ES modules is not supported.
require() of /mnt/c/workgit/orm/.next/server/pages/api/user/signup.js from /mnt/c/workgit/orm/node_modules/next/dist/next-server/server/next-server.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
Instead rename signup.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from /mnt/c/workgit/orm/package.json.

    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1268:13)
    at Module.load (internal/modules/cjs/loader.js:1100:32)
    at Function.Module._load (internal/modules/cjs/loader.js:962:14)
    at Module.require (internal/modules/cjs/loader.js:1140:19)
    at require (internal/modules/cjs/helpers.js:75:18)
    at DevServer.handleApiRequest (/mnt/c/workgit/orm/node_modules/next/dist/next-server/server/next-server.js:48:175)
    at processTicksAndRejections (internal/process/task_queues.js:93:5)
    at async Object.fn (/mnt/c/workgit/orm/node_modules/next/dist/next-server/server/next-server.js:40:218)
    at async Router.execute (/mnt/c/workgit/orm/node_modules/next/dist/next-server/server/router.js:38:67)
    at async DevServer.run (/mnt/c/workgit/orm/node_modules/next/dist/next-server/server/next-server.js:49:494) {
  code: 'ERR_REQUIRE_ESM'

Answer №1

If your ormconfig file's migrations/entities property points to .ts files, you may encounter a problem. One solution is to override these properties when passing them to the createConnection function like this:

createConnection({
  ...config,
  entities: [Contact],
  migrations: []
});

For more information, see this discussion on Github: https://github.com/typeorm/typeorm/issues/6241#issuecomment-643690383

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

Learn how to host your Next.js application on Cloudflare Pages while also integrating LaunchDarkly feature flags

Recently, I had the opportunity to deploy my Next.js 13 app to the Edge on Cloudflare Pages using experimental: { runtime: 'experimental-edge' }. However, due to some revised requirements, I now need to integrate our feature flag dependency from ...

What is the reason that the values in the select option only appear once it has been clicked on?

After loading or reloading the page, I am experiencing an issue where the select options do not appear on the first click and the values are not displayed until the second click. Any assistance would be greatly appreciated! I am still new to coding, so ple ...

Using Angular 4 for HTML 5 Drag and Drop functionality

I have been working on integrating native HTML 5 drag & drop functionality into my angular application. While I have successfully implemented the drag and dragOver events, I am facing an issue with the drop event not firing as expected. Here is the snipp ...

What is the proper way to add a string to a TypeScript array?

When attempting to add a string to a TypeScript array, I am encountering an error stating 'cannot push to undefined'. Is this the correct approach, or should I be using the spread operator instead? api.ts const api: IConfigName = {name: "getKey ...

Why isn't the POST operation functioning properly while all other CRUD operations are working?

After extensive testing with Postman, I found that all CRUD operations are functioning correctly, including POST. However, the issue arises when trying to make a POST request in the frontend app. Despite hours of debugging, I am still encountering errors. ...

How to bring in images from the assets folder using React and Typescript

I'm facing an issue where direct image importing is working, but when using object types, it's not functioning properly. Why could this be happening? I am currently working with "react": "^16.12.0" and "typescript": "~3.7.2" // ./src/assets/baby ...

Optimal strategies for managing subscriptions in Angular

I'm currently pondering about the concept of angular subscription and unsubscription. The amount of information available on this topic is overwhelming, making it hard for me to navigate through. When is the right time to unsubscribe from a subscript ...

Retrieving URL parameters within an API route handler in Next.js

Within my client component called GetUserInfoButton, I initiate a GET request using the URL format of http://localhost:3000/test/users/[id]. The [id] in this URL is represented by an alphanumeric sequence similar to MongoDb. My intention within the file a ...

Decide whether to fulfill or deny a Promise at a later time in

When working on an Angular2/TypeScript project, a dialog is shown and the system returns a Promise object to the caller. This Promise will be resolved after the user closes the dialog. The interface of the Promise class does not include methods like resol ...

Developing a Javascript object using Typescript

Trying my hand at crafting a TypeScript object from JavaScript. The specific JavaScript object I'm attempting to construct can be found here: https://cdnjs.cloudflare.com/ajax/libs/chess.js/0.10.2/chess.js In the provided JavaScript example, the obj ...

My Next.js application is successfully making Axios API calls to my localhost while running on the server-side

In my Next.js and React application, I am utilizing the axios library. Initially, I was able to successfully call the API from the server using getStaticProps() and render the initial data properly. However, when attempting to fetch more data from the clie ...

Resolving conflicts between AbortSignal in node_modules/@types/node/globals.d.ts and node_modules/typescript/lib/lib.dom.d.ts within an Angular project

An issue occurred in the file node_modules/@types/node/globals.d.ts at line 72. The error message is TS2403: Subsequent variable declarations must have the same type. Variable 'AbortSignal' should be of type '{ new (): AbortSignal; prototype ...

What are the reasons for the failure of caching when retrieving data from the server using fetch?

I have developed an application that displays a list of posts, and when the user clicks on a post, they are redirected to a single details page for that post. index.js (list of posts) export default function Home(props) { const [postData, setPostData] ...

cssclassName={ validatorState === RIGHT ? 'valid' : 'invalid' }

Is there a way to dynamically add different classes based on validation outcomes in React? My current implementation looks like this: className={ validatorState === RIGHT ? 'ok' : 'no' } However, I also need to handle cases where the ...

Guide on transitioning a client-side "authentication validation" setup to the updated app routing system

After successfully stabilizing the app router, I made the decision to transition from the old pages folder. Prior to implementing the app router, it was common practice to utilize the getserversideprops function to verify if a user is logged in. If not, t ...

Customizing App (directory) elements in next.js 13

Imagine having this directory organization: https://i.stack.imgur.com/Hd5gu.png Is there a method for loading the component from the custom folder instead of the default one in the app folder? In case the custom folder does not have that component, can t ...

Transfer only designated attributes to object (TS/JS)

Is it feasible to create a custom copy function similar to Object.assign(...) that will only copy specific properties to the target? The code snippet I have is as follows: class A { foo?: string; constructor(p: any) { Object.assign(this, p ...

It appears that using dedicated objects such as HttpParams or UrlSearchParams do not seem to work when dealing with Angular 5 and HTTP GET query parameters

I'm facing a perplexing issue that I just can’t seem to figure out. Below is the code snippet making a call to a REST endpoint: this.http.get<AllApplicationType[]>(environment.SUDS_API_SERVICE_URL + environment.SUDS_ALL_APPLICATIONS_URL, this ...

Encountering a Next.js TypeScript Build Error related to the Type 'OmitWithTag<InputFormProps, keyof PageProps, "default">' issue

`I am currently working on a project in Next Js using TypeScript. During the build process with npm run build, I encountered the following errors in the terminal: # Type 'OmitWithTag<InputFormProps, keyof PageProps, "default">' do ...

Exploring Blob functionality in TypeScript?

I defined a global Blob object: declare global { interface Blob { prototype: Blob; new (name: string, url: string): Blob; } } It is functioning correctly in this code snippet: export const blobToFile = (blob: Blob) => { let file: File | n ...