Recently, I refactored my Nuxt Token Authentication module to utilize Nitro's default db0
layer instead of Prisma. The transition was relatively smooth, though I encountered a few undocumented or not clearly documented aspects along the way. Here's a rundown of my experience to hopefully save you some time.
Initial Struggle
According to the Nitro documentation, you can use an object for the database
in the nuxt.config.ts
file. However, at the time of writing, this is not fully supported. Only a boolean value is accepted, which took some troubleshooting to uncover.
Configuration Example
Instead of this:
export default defineNuxtConfig({
nitro: {
experimental: {
database: {
driver: 'sqlite',
options: {
// name: 'something', path: '/some/path'
}
}
}
}
})
You should use:
export default defineNuxtConfig({
nitro: {
experimantal: {
database: true // this is the correct setup currently
}
}
})
Database Connection Issues
I initially faced issues with my app not being able to communicate with the prepared database. The error messages were misleading, complaining about a missing users
table, what I already created. After some digging, I discovered that if the database does not exist at the default path /.data/db.sqlite3
, Nitro silently creates it.
Error: SQLITE_ERROR: no such table: users
This error suggests a missing table, but the root cause was I tried to use a database in a non default path and name.
Auto-import Issues
Another hiccup I encountered was with useDatabase()
. While it worked at runtime without issues, TypeScript could not find it, causing type errors. This auto-import problem can be a bit annoying during development.
// UseDatabase usage
const db = useDatabase();
TypeScript error: Cannot find name 'useDatabase'.ts(2304)
I did not found a solution yet to this problem.
A Known Issue with Table Names and Fields
A known issue with db0
is that table names and fields cannot be used without curly braces {}. This is tracked in GitHub issue #77.
// incorrect, errors out
const { rows } =
await db.sql`SELECT * FROM ${options.authTable} WHERE ${options.tokenField} = ${strippedToken} LIMIT 1`;
// correct
const { rows } =
await db.sql`SELECT * FROM {${options.authTable}} WHERE {${options.tokenField}} = ${strippedToken} LIMIT 1`;
Conclusion
Switching to Nitro's db0
layer was a valuable learning experience. Despite the challenges with documentation and some minor bugs, the process was fairly straightforward. I hope sharing these insights can help other developers transition smoothly and avoid some of the pitfalls I encountered.
Feel free to leave comments or ask questions if you run into any issues or have further tips to share!
Let's slap into the code!
Top comments (0)