What is the best way to handle asynchronous actions while initializing a database in Next.js?

My goal is to create tables during the database initialization stage with a structure like this:

CREATE TABLE IF NOT EXISTS users (
  "id" SERIAL PRIMARY KEY,
  "created_at" TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  "name" TEXT NOT NULL,
)

Ordinarily, setting this up in a standard server environment would be straightforward (even in an async setup), but Nextjs lacks a centralized "init" stage. I have devised the following workaround so far:

import { setupTables } from "./tables";
import { getDBSingleton } from "./init";


let isInitialized = false;

export async function getDB() {
  const scope = getDBSingleton();

  if (!isInitialized) {
    await setupTables(scope.db);
    isInitialized = true;
  }

  return scope;
}

The getDBSingleton() function I am using is based on this response: Where should I initialize pg-promise

While this workaround functions as intended, it necessitates calling await getDB() within every single function that interacts with the database, rather than just once per module.

Is there a more efficient way to handle this?

Answer №1

A strategic approach is to execute migrations in a standalone script prior to initiating the build process.

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

Comparing the integration of apollo-client in next.js using `next-with-apollo` with the alternative method recommended in the next.js documentation FAQ (without relying on `getDataFromTree

Exploring the Contrasting Approaches of Implementing "apollo-client in next.js" in next-with-apollo npm library versus the method outlined in the next.js documentation. For the approach chosen by next.js for Apollo client integration, visit: https://githu ...

What exactly does "context" refer to in the context of TypeScript and React when using getServerSideProps?

As a beginner in coding, I have a question regarding a specific syntax I recently encountered. I am confused about this particular line of code and couldn't find any helpful explanations online: export async function getServerSideProps(context: GetSer ...

Changing the names of the remaining variables while object destructuring in TypeScript

UPDATE: I have created an issue regarding this topic on github: https://github.com/Microsoft/TypeScript/issues/21265 It appears that the syntax { ...other: xother } is not valid in JavaScript or TypeScript, and should not compile. Initial Query: C ...

Generating build time arguments from a file using Docker Compose

In my current project, I am facing the challenge of adapting an existing set up where the .env file locations are predetermined. While I understand that using a .env at the root of the project could simplify variable substitutions, it is not feasible in th ...

ESLint and Prettier are butting heads when trying to run their commands consecutively

My package.json file includes two commands: "format": "prettier --write \"{src,{tests,mocks}}/**/*.{js,ts,vue}\"", "lint": "eslint . -c .eslintrc.js --rulesdir eslint-internal-rules/ --ext .ts,.js,.vue ...

`Finding an efficient solution to handling the intricate state of a group of components in Nextjs/ReactJS``

My form for creating new recipes includes a dynamic list of ingredients that users can add to and remove from. You can see an example here. The Ingredient Component within the form consists of quantity, unit, and title input fields. I'm struggling wi ...

Convert JSON data into an array of strings that are related to each other

I'm encountering an issue with converting JSON into a string array I must convert a JSON into a string array to dynamically INSERT it into our database, as I need this to work for any type of JSON without prior knowledge of its structure. Here is th ...

Guide on setting up Tailwind CSS and material-tailwind concurrently within the tailwind.config.js configuration file

I am looking to integrate both Tailwind and Material Tailwind in a Next.js 14 project. Below is my customized tailwind.config.ts file (already configured with Tailwind CSS): import type { Config } from 'tailwindcss' const config: Config = { ...

Using `import * as speechCommands from "@tensorflow-models/speech-commands"` is functional in React, but unfortunately does not operate correctly in NextJS

Currently, I am in the process of reworking a React application to be compatible with NextJS, as I need to utilize the backend accessed through /app/api route. However, I have encountered the following error: ./node_modules/@tensorflow-models/speech-comma ...

Using Typescript alongside Angular 1.6 and browserify for your development needs

Currently navigating the world of working with Angular types in TypeScript and bundling code using Browserify. After following a TypeScript guide related to Gulp, I utilized npm to install the Angular types and put together this simple ts file. import * a ...

Struggling to convert a JSON response into an object model using TypeScript in Angular?

I'm encountering a problem when trying to convert a JSON response into an object. All the properties of my object are being treated as strings, is that normal? Below is my AJAX request: public fetchSingle = (keys: any[]): Observable<Medal> =&g ...

group items into ranges based on property of objects

I've been grappling with this issue for far too long. Can anyone provide guidance on how to tackle the following scenario using JavaScript? The dataset consists of objects representing a date and a specific length. I need to transform this list into a ...

What is the solution for resolving the JavaScript runtime error '0x800a1391 - 'require' is undefined'?

As a C# developer with limited web experience, I am currently diving into learning Typescript. However, I seem to be facing a roadblock in the form of an error message. 0x800a1391 - JavaScript runtime error: 'require' is undefined To provide so ...

Issues with material styling loading on the production build

I am currently working on a project using Nextjs and Material UI. The project runs smoothly in development mode, but encounters styling issues when built for production. Specifically, upon navigating to a second page, certain components like Dialog load wi ...

An issue has occurred: The necessary parameter (Slug) was not included as a string in the getStaticPaths function for the /post/[Slug] route

Hello, I've recently embarked on a tutorial journey to create the ultimate Modern Blog App using React, GraphQL, NextJS, and Tailwind CSS. However, I encountered an error that's giving me some trouble specifically when trying to access a post. He ...

I am encountering an issue with NEXTjs where SVG images are not displaying on my website

Issues with SVG Import in NextJS Website I am encountering difficulties while trying to import an SVG file into my NextJS website. I have attempted to use the <Image /> tag, as well as the <img /> and <svg> tags. While Webstorm recognize ...

Having trouble with the "Vs Code nx console generate" command? It seems that there are no flags available to configure

My issue involves the nx console extension installed in my Visual Studio Code. Every time I attempt to use the generate command for components, services, or libraries, I receive an error message stating "ng generate @schematics/angular:component This com ...

Enhancing nested structures in reducers

Currently, I am utilizing react, typescript, and redux to develop a basic application that helps me manage my ingredients. However, I am facing difficulties with my code implementation. Below is an excerpt of my code: In the file types.ts, I have declared ...

Angular's implementation of a web socket connection

I am facing an issue with my Angular project where the web socket connection only opens upon page reload, and not when initially accessed. My goal is to have the socket start as soon as a user logs in, and close when they log out. Here is the custom socke ...

Show a dropdown menu based on a certain condition in Angular

Is there a way to conditionally display select options like this? <select id="updateType" class="form-control" formControlName="updateType"> <option value="personalDetails">Personal</option> <option value="addressD ...