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

Tips for passing parameters from an anchor click event in TypeScript

Is it possible to send parameters to a click event from an anchor element, or should we not pass params at all? Here is the function I am using: const slideShow = (e: React.MouseEvent<HTMLAnchorElement> | undefined): void => { console.lo ...

How can I set up BaconJS in conjunction with Webpack and CoffeeScript?

Currently in the process of transitioning old code to Webpack and encountering some issues... Utilizing a dependency loader in TypeScript import "baconjs/dist/Bacon.js" And a module in CoffeeScript @stream = new Bacon.Bus() Upon running the code, I en ...

The compatibility issue arises when using Material UI Portal with TypeScript, specifically with the 'children' property types

When rendering a component using Material-UI Portal that includes several Material UI buttons, the following code is used: <Portal container={this.myContainer}> <Button onClick={this.handleClick}>Do something</Button> //other but ...

Transitioning a codebase from @angular-builders/custom-webpack to NX for project optimization

I need help migrating my Angular project from using "@angular-builders/custom-webpack" build targets to transitioning to an integrated NX monorepo. When I run the command npx nx@latest init --integrated, I receive the following warning: Unsupported build ...

steps to create a personalized installation button for PWA

Looking to incorporate a customized install button for my progressive web app directly on the site. I've researched various articles and attempted their solutions, which involve using beforeinstallprompt. let deferredPrompt; window.addEventListener(& ...

The required property '0' is not found in the type 'any[]' but it is needed in the type '[{ post_id: string; title: string; }]'

I have gone through this post but I am still struggling to understand the issue. Why am I unable to pass this array to the update call? // create a new object with updated post properties const newPost = await this.postRepository.create(data); await thi ...

React Native ScrollView ref issue resolved successfully

I'm trying to automatically scroll to the bottom of a flatlist, so here's what I have: const scrollViewRef = useRef(); //my scroll view <ScrollView ref={scrollViewRef} onContentSizeChange={() => { scrollViewRef.current.scr ...

Using a custom TypeScript wrapper for Next.js GetServerSideProps

I developed a wrapper for the SSR function GetServerSideProps to minimize redundancy. However, I am facing challenges in correctly typing it with TypeScript. Here is the wrapper: type WithSessionType = <T extends {}>( callback: GetServerSideProps&l ...

DateAdapter not found within Angular/Material/Datepicker - Provider not available

I need assistance with: angular / material / datepicker. My test project is running smoothly and consists of the following files: /src/app/app.module.ts import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from ' ...

Adding strings in Typescript

I have the following code snippet: let whereClause = 'CurLocation =' + GS + ' and Datediff(DD,LastKYCVerified,GetDate()) >= 180 and CreditCard = ' + 'ACTIVE ' + &ap ...

What could be causing the ReferenceError: self is not defined issue I'm encountering as I try to import a client-side library?

Having trouble creating a custom xterm react component within Next.js, I'm currently stuck on an unfamiliar error message. I am attempting to import a client-side npm module named xterm, but whenever I include the import line, the application crashes ...

Ionic Framework: Implementing a search bar in the navigation bar

I am looking to include a search icon in the navbar of my Ionic project <ion-navbar> <ion-buttons left> <button ion-button menuToggle> <ion-icon name="menu"></icon-icon> </button> </ion-bu ...

Is it possible to both break down a function parameter and maintain a named reference to it at the same time?

When working with stateless functional components in React, it is common to destructure the props object right away. Like this: export function MyCompoment({ title, foo, bar }) { return <div> title: {title}, ...</div> } Now ...

One-page application featuring an index.html page that is generated dynamically

In the development of my app, I am utilizing Expo + React Native. The concept involves providing each client with their unique URL, although essentially they are all accessing the same app. This setup presents a challenge when it comes to implementing Goog ...

The global.css base is not properly implementing the Tailwind styles

My global.css file contains some styling: @tailwind base; @tailwind components; @tailwind utilities; @layer base { .body { @apply bg-[#141414] text-white; // This should change the body color, but it's not working } } @layer componen ...

Determine the index of items within an array of objects in Lodash where a boolean property is set to true

I am new to using lodash after transitioning from C# where I occasionally used LINQ. I have discovered that lodash can be utilized for querying in a LINQ-style manner, but I'm struggling to retrieve the indexes of items in an array of objects with a b ...

What is the equivalent of html script tags in Webpack 2?

I recently downloaded a new npm module that suggests including the following code in my project: <link href="node_modules/ng2-toastr/bundles/ng2-toastr.min.css" rel="stylesheet" /> <script src="node_modules/ng2-toastr/bundles/ng2-toastr.min.js"&g ...

Uncovering the perfect body proportions using Webpack and SystemJS

In the process of developing an Angular2 library that needs to work with both SystemJS and Webpack, I encountered a situation where I had to detect the height and width in pixels of the body tag to set dimensions for child tags. However, the behavior of An ...

The declaration file for the module 'tailwind-scrollbar' could not be located

Currently, I am in the process of utilizing Tailwind packages for a Next.js application, however, I have encountered an issue that has proved to be quite challenging to resolve. Every time I attempt to add a "require" statement to my tailwind.config.js fil ...

Employ a type as a function in Typescript programming

Looking for a way to convert an ID into an object using a specific type. The type accepts personId as a string parameter and returns either a Person or undefined. export type FindPerson = (personId: string) => Person | undefined; I have multiple person ...