Most Next.js users use powerful backend databases such as Postgresql to serve the pages’ content and generate static pages, but often it’s an overkill and you can use simpler configuration with sqlite as underlying database to serve your content.
In this tutorial I’m going to explain step by step how you can use a simple sqlite instance in conjunction with Next.js 15 to serve your static pages.
Why use sqlite instead of Postgres with Next.js
Postgres is often the first choice for Next.js because it’s widely available, and conveniently provided as one of the db integration within the Vercel.com platform through the neon.tech provider.
However, when you’re running a basic website or blog, even with thousands of entries and high traffic there’s no need to use Postgres and you can easily choose sqlite as your backend db, because it’s extremely robust for concurrent reads and it’s contained within a standalone file meaning you don’t need to run nor maintain any server infrastructure or pay for any integrations from Vercel.
Another upside of this solution is that you don’t pay for any server because everything is contained within your Next.js project and while generating static pages the app only fetches data from the local sqlite file making it ideal for projects that primary use static generated pages on build time.
If you’re using Visual Studio Code there’s also a neat extension SQLite Viewer for VS Code (with over 1.5 million installs at the time of writing this article)allowing you to browse and manipulate data directly in the editor, without any external tools!
How to install sqlite for Next.js
For convenience’s sake we will be using sqlite with Prisma ORM, which vastly simplifies data manipulation and reads. If you don’t know how to install and configure Prisma in Next.js make sure to read our tutorial first.
OK, let’s go back to work. First, install Prisma and sqlite modules:
npm install prisma @prisma/client sqlite3
Once you’ve initialized sqlite and configured your Prisma models and generated Prisma client (again, all this is explained here) you must switch the sqlite as your underlying database by modifying the schema.prisma
file:
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "sqlite"
url = env("DATABASE_URL")
}
Now, edit the .env
file and specify file path to the sqlite database file:
DATABASE_URL="file:./mydatabase.sqlite"
Take note, that we’re using the path to the local file you’re storing in your Next.js project folder. This makes things so much easier. No more setting up of external servers!
Migrate and create initial database
When everything is set up simply run:
npx prisma migrate dev --name init
To initialize your sqlite database with the defined models and you’re all set.
You can now import Prisma client and use the models definitions along with TypeScript intellisense in your API routes or pages for static content generation.
That’s it, happy coding!