#Best place to run a startup script (ie Database migration)

1 messages · Page 1 of 1 (latest)

cedar ruin
#

Hi,
I'm trying to execute a SQL migration script when my nuxt server starts but I'm not sure where the best place to do this is?

I've tried as a plugin but it seems to execute at every request so whilst it works, its not practical for obvious reasons:

plugins/migrate.server.ts:

import { migrateDb } from './database'

export default defineNuxtPlugin(async () => {
  const runtimeConfig = useRuntimeConfig()
  await migrateDb(runtimeConfig.databaseUrl)
})

Next up I've tried to execute it in a hook, but this doesnt seem to work as my database url is set as an env variable NUXT_DATABASE_URL in my .env file but it says its an empty string:

  runtimeConfig: {
    databaseUrl: ''
  },
  hooks: {
    async ready(nuxt) {
      console.log(nuxt.options.runtimeConfig) //runtimeConfig.databaseUrl === ''
      const runtimeConfig = nuxt.options.runtimeConfig
      await migrateDb(runtimeConfig.databaseUrl)
    },
  },

Any idea how I can resolve this? Thanks.

cedar ruin
#

Okay I think I've figured it out, I was close with the plugin approach, instead of having it in the plugins folder, I moved it to server/plugins folder, now it only runs once, and not on every request

prime scaffold
#

This help me a lot, but got confused because I was assuming that the pluging run on every request but I place a log in the hook from the nitro app lol

runic mirage
#

Question - does the plugin code execute after build and deployment?

In other words, on app start up?

What if the migration fails? Do you have a deployed application with DB that is behind on migrations?

marsh kiln
#

How about using nitro task and manually running it once?

prime scaffold
#

One of the issues that I'm currently facing is that the build from nuxt don't contain the migrations from my layer, so the only way that I manage to do it is to have ci pipeline that is trigger manually, to deploy to prod that will first run DB migrate then deploy the build to prod

#

I was looking for a way to do it automatically like with spring boot and flyway migrations run before application start

#

In the nuxt hub they have auto migrations, but it seems like it is at build time but I don't know tbh