Now that you have your database schema and migrations set up, you can start querying your database.
NuxtHub provides two ways to import the database client:
@nuxthub/dbUse @nuxthub/db to import the database client. This works everywhere, including in Nuxt server routes and external bundlers like Workflow:
import { db, schema } from '@nuxthub/db'
hub:dbThe virtual module hub:db is still supported for backwards compatibility (Nuxt only):
import { db, schema } from 'hub:db'
db and schema are auto-imported on the server-side, so you can use them directly without importing.import { db, schema } from '@nuxthub/db'
export default eventHandler(async (event) => {
return await db.query.users.findMany()
// or
return await db.select().from(schema.users)
})
import { db, schema } from '@nuxthub/db'
export default eventHandler(async (event) => {
const { name, email } = await readBody(event)
return await db
.insert(schema.users)
.values({
name,
email,
createdAt: new Date()
})
.returning()
})
import { db, schema } from '@nuxthub/db'
export default eventHandler(async (event) => {
const { id } = getRouterParams(event)
const { name } = await readBody(event)
return await db
.update(schema.users)
.set({ name })
.where(eq(tables.users.id, Number(id)))
.returning()
})
import { db, schema } from '@nuxthub/db'
export default eventHandler(async (event) => {
const { id } = getRouterParams(event)
const deletedUser = await db
.delete(schema.users)
.where(eq(schema.users.id, Number(id)))
.returning()
if (!deletedUser) {
throw createError({
statusCode: 404,
message: 'User not found'
})
}
return { deleted: true }
})
The @nuxthub/db import works seamlessly with external tools that bundle your code independently, such as Workflow.
Workflow is a library for building and running durable, reliable, and scalable background jobs in TypeScript. Here's how to use NuxtHub Database with Workflow:
import { db, schema } from '@nuxthub/db'
import { lt } from 'drizzle-orm'
export default async function cleanupInactiveUsers() {
// Delete users who haven't logged in for 90 days
const ninetyDaysAgo = new Date(Date.now() - 90 * 24 * 60 * 60 * 1000)
const deleted = await db
.delete(schema.users)
.where(lt(schema.users.lastLoginAt, ninetyDaysAgo))
.returning()
return {
deletedCount: deleted.length,
deletedUserIds: deleted.map(u => u.id)
}
}
When you build your Nuxt application:
node_modules/@nuxthub/db/hub:db virtual module remains available for Nuxt server routes (backwards compatibility)@nuxthub/db package is auto-generated during development and build. You don't need to add it to your package.json.nuxt dev or nuxt buildserver/db/schema.ts files are the only place you define your schema