Cloudflare Pages NextJs + D1 Database ᐧ My experience developing sharejson
Shrihari Mohan
Posted on February 3, 2024
The biggest challenge I encountered during Next.js development was the lack of hot reloading when using a D1 database locally. We have to use experimental-edge
when using getServerSideProps
.
Development is time consuming!
npm run dev
will not give D1 database bindings
I have to rebuild the entire project every time I make a change, even a minor one. This can be very time-consuming.
I managed to complete sharejson.com because it's a single-page application with only one table. However, for larger projects with more tables, I wouldn't recommend using D1 due to the significant development time required. It simply doesn't feel efficient in these scenarios.
Test your Next.js application with hot reload while mocking database responses and test the database logic later to make development easier.
Setting up Nextjs Pages & D1 Database
npm create cloudflare@latest my-next-app -- --framework=next
Creates a new Next.js project with pages setup. Once we have the wrangler cli , we can directly deploy app.
We have to change the env.d.ts
for bindings.
declare global {
namespace NodeJS {
interface ProcessEnv {
[key: string]: string | undefined;
DATABASE: D1Database;
}
}
}
export { };
After signing up with Cloudflare, you can create a database on their platform and access environment variables. Add wrangler.toml
file with D1 details.
[[d1_databases]]
binding = "DATABASE"
database_name = "db"
database_id = "database-id-from-website"
I've isolated database operations in the src/server
folder. However, the db
variable remains undefined
during npm run dev
as hot reloading isn't supported. For database access, use npm run pages:dev
, but be aware that this disables hot reloading.
const db = process.env.DATABASE
export const selectFromJsons = async (id: string) => {
const stmt = db.prepare(`select * from jsons where id = ?1`).bind(id)
const results = await stmt.first()
return results
}
Overall, using D1 and Pages has been a positive experience, as it currently runs everything for free.
Posted on February 3, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.