SQLite flat file database for local Next.js statically generated site
Answered
White-throated Robin posted this in #help-forum

White-throated RobinOP
Am I able to use a flat file database like sqlite in conjunction with next.js or do I need to "host" the database service first? My site is statically generated html but the content is stored in a database. If this is possible what libraries are recommended?
27 Replies

you can use any db in nextjs
I also use sqlite for quick prototyping and move to another db when I am ready to ship

@Yi Lon Ma I also use sqlite for quick prototyping and move to another db when I am ready to ship

White-throated RobinOP
thanks for the quick response, what libraries are you using? "sqlite3"?

prisma
but yeah I've also used sqlite3 and it also works good

@Yi Lon Ma but yeah I've also used sqlite3 and it also works good

White-throated RobinOP
https://stackoverflow.com/questions/67493040/next-js-ssr-with-local-sqlite-unable-to-open-database-file
were you able to get it working on SSR? i know final product is SSG but when prototyping I use server rendered.
were you able to get it working on SSR? i know final product is SSG but when prototyping I use server rendered.

this is with vercel
vercel, afaik, is read only file system
you will need a sqlite service for this
something like turso

White-throated RobinOP
but on local we don't need that correct?
npm run dev environment

yea you can use local sqlite in dev

White-throated RobinOP
i'm getting the same sqlite error unable to open database file. not too sure why

locally?

White-throated RobinOP
yes
import sqlite3 from "sqlite3";
import { open, Database } from "sqlite";
// Let's initialize it as null initially, and we will assign the actual database instance later.
let db: any = null;
// Define the GET request handler function
export async function GET(req, res) {
// Check if the database instance has been initialized
if (!db) {
// If the database instance is not initialized, open the database connection
db = await open({
filename: "./mobile.db", // Specify the database file path
driver: sqlite3.Database, // Specify the database driver (sqlite3 in this case)
});
}
// Perform a database query to retrieve all items from the "items" table
const items = await db.all("SELECT * FROM paths");
// Return the items as a JSON response with status 200
console.log(items);
return new Response(JSON.stringify(items), {
headers: { "Content-Type": "application/json" },
status: 200,
});
}

what is
open

White-throated RobinOP
function from "sqlite" package
import { open, Database } from "sqlite";

White-throated RobinOP
i'm just following this https://plainenglish.io/blog/using-sqlite-with-next-js-13 tutorial

@Yi Lon Ma also, is the path correct

White-throated RobinOP
yes the database is in the same directory as the page executing the code

try to use just 1 package
Answer

White-throated RobinOP
alright