Blog

5 min read

Connecting a MySQL Database in Nuxt with Drizzle ORM

Connect MySQL to Nuxt with Drizzle ORM: define a table, apply a migration, reuse a connection pool and query articles from a server route.

Ask my AI assistant
Connecting a MySQL Database in Nuxt with Drizzle ORM Image

For a Nuxt application with a MySQL database, I want to define my tables in TypeScript and query them from server routes. Drizzle ORM lets me do that without writing a separate model class for every table.

In this article, I want to show you how to connect MySQL to Nuxt, define a table for published articles and read those articles through an API route.

Set Up the Project

We need a Nuxt application running on a Node.js server and a MySQL database. The connection below uses the mysql2 driver; it is not an example for an edge runtime.

If you don't have a Nuxt project yet, create one:

pnpm create nuxt my-nuxt-drizzle-app
cd my-nuxt-drizzle-app

Install Drizzle and the MySQL driver, plus Drizzle Kit for migrations:

pnpm add drizzle-orm mysql2
pnpm add -D drizzle-kit dotenv

drizzle-orm/mysql2 is an import path inside drizzle-orm, not another package to install. The Drizzle MySQL documentation describes the adapter.

We will keep the schema in server/database/schema.ts, the connection helper in server/utils/drizzle.ts and the API handler in server/api/articles.get.ts. All database access stays on the server.

Configure the Database URL

First, declare the database URL in Nuxt's runtime configuration:

nuxt.config.ts
export default defineNuxtConfig({
  runtimeConfig: {
    private: {
      databaseUrl: '',
    },
  },
})

Then add your connection string to .env:

.env
NUXT_PRIVATE_DATABASE_URL=mysql://app_user:local_password@localhost:3306/articles

Replace the example credentials with those for your database. Keep .env out of version control, and set the same environment variable on your production server. Don't put the URL under runtimeConfig.public, since that would expose it to the browser.

Define the Articles Table

Let's create the schema for our published articles:

server/database/schema.ts
import { datetime, int, mysqlTable, varchar } from 'drizzle-orm/mysql-core'

export const publishedArticles = mysqlTable('published_articles', {
  id: int('id').primaryKey().autoincrement(),
  publishedAt: datetime('published_at').notNull(),
  title: varchar('title', { length: 255 }).notNull(),
  url: varchar('url', { length: 512 }).notNull().unique(),
})

The TypeScript property publishedAt maps to the SQL column published_at. We will use publishedAt in our queries. The URL is a bounded varchar with a unique constraint, so inserting the same URL twice fails.

Drizzle can infer a row type from this definition with typeof publishedArticles.$inferSelect. We don't need to maintain a second interface with the same fields.

Create and Apply a Migration

The TypeScript schema doesn't create the table by itself. Configure Drizzle Kit so it knows where the schema is and which database to connect to:

drizzle.config.ts
import 'dotenv/config'
import { defineConfig } from 'drizzle-kit'

const databaseUrl = process.env.NUXT_PRIVATE_DATABASE_URL
if (!databaseUrl) {
  throw new Error('NUXT_PRIVATE_DATABASE_URL is missing')
}

export default defineConfig({
  dbCredentials: {
    url: databaseUrl,
  },
  dialect: 'mysql',
  out: './server/database/migrations',
  schema: './server/database/schema.ts',
})

Drizzle Kit runs outside Nuxt, so it cannot use useRuntimeConfig(). The dotenv/config import loads the local .env file for this command.

Generate the migration, inspect the SQL and apply it to your development database:

pnpm exec drizzle-kit generate
pnpm exec drizzle-kit migrate

Commit the generated migration files with your schema change. Review migrations before running them against production, especially when a change removes a column or alters existing data.

Reuse a Connection Pool

We can now create the database helper:

server/utils/drizzle.ts
import { drizzle } from 'drizzle-orm/mysql2'
import mysql from 'mysql2/promise'

function createDatabase() {
  const { databaseUrl } = useRuntimeConfig().private
  if (!databaseUrl) {
    throw new Error('Database URL is missing')
  }

  const pool = mysql.createPool({
    connectionLimit: 5,
    uri: databaseUrl,
  })

  return drizzle({ client: pool })
}

let database: ReturnType<typeof createDatabase> | undefined

export function useDrizzle() {
  database ??= createDatabase()
  return database
}

The helper creates the pool on its first call and reuses it for later requests in the same server process. Opening a new connection for every query would add connection overhead and require us to close each connection ourselves.

The pool limit of five is an example, not a recommended value for every app. If you run several server instances, each has its own pool. Their combined connections must fit within your database's limit. The mysql2 documentation explains pool configuration.

For a long-running server, close the pool during shutdown as part of your deployment's lifecycle handling. Serverless deployments also need connection limits suited to the number of instances they can start.

Read Articles From a Server Route

Create a GET endpoint that returns the latest 100 articles:

server/api/articles.get.ts
import { desc } from 'drizzle-orm'
import { publishedArticles } from '../database/schema'
import { useDrizzle } from '../utils/drizzle'

export default defineEventHandler(async () => {
  const db = useDrizzle()

  return db.select({
    id: publishedArticles.id,
    publishedAt: publishedArticles.publishedAt,
    title: publishedArticles.title,
    url: publishedArticles.url,
  })
    .from(publishedArticles)
    .orderBy(desc(publishedArticles.publishedAt))
    .limit(100)
})

We import the table explicitly, use the field names from the schema and limit the result. Nuxt's server route returns the rows as JSON at /api/articles.

For a Nuxt 4 app, a page can fetch that endpoint like this:

app/pages/articles.vue
<script setup lang="ts">
const { data: articles, error, status } = await useFetch('/api/articles')
</script>

<template>
  <p v-if="status === 'pending'">Loading articles...</p>
  <p v-else-if="error" role="alert">Articles could not be loaded.</p>
  <ul v-else>
    <li v-for="article in articles" :key="article.id">
      {{ article.title }}
    </li>
  </ul>
</template>

The page receives article data. It never imports the database helper or receives the connection string. In a Nuxt 3 app using the older directory structure, put the page in pages/articles.vue instead.

Check the Setup

After applying the migration, start Nuxt and request /api/articles. An empty table should return an empty array. Insert a test article in your development database, call the endpoint again and check the returned fields. Add another article with a later publication date to verify the ordering.

For automated coverage, run the migration and query against a separate MySQL test database. A mocked query can verify that a handler calls a helper, but it won't catch an invalid SQL column definition or a failed migration.

Before deploying, configure database TLS according to your provider's instructions and use a database user with only the permissions the app needs. A migration user can have separate permissions for changing tables. If you add filters or write endpoints, validate their input at the server boundary.

Conclusion

I like having the table definition and query code in TypeScript. In this example, changing a schema property also changes what TypeScript expects when we query that table.

The part I would pay attention to in production is connection management. The schema can be correct while too many application instances still exhaust the database's connection limit. Reusing a pool is a starting point; its size needs to match the deployment.

My Nuxt Starter Kit also uses Drizzle if you want to see how it fits into a larger Nuxt application.
If you found this article helpful.You will love these ones as well.
Create an RSS Feed With Nuxt 3 and Nuxt Content v2 Image

Create an RSS Feed With Nuxt 3 and Nuxt Content v2

How I Replaced Revue With a Custom-Built Newsletter Service Using Nuxt 3, Supabase, Serverless, and Amazon SES Image

How I Replaced Revue With a Custom-Built Newsletter Service Using Nuxt 3, Supabase, Serverless, and Amazon SES

Why I Developed My Own Nuxt Starter Kit for SaaS Products Image

Why I Developed My Own Nuxt Starter Kit for SaaS Products

Build and Deploy a Serverless GraphQL React App Using AWS Amplify Image

Build and Deploy a Serverless GraphQL React App Using AWS Amplify