UPDATE (19 jun 2023): In the meantime I’ve started using GisCus for comments, read more about why and how here.
After I created my blog platform using Astro, the next thing on my list was to make it possible for people to (anonymously) leave comments on blog posts.
For this I needed to add a database to my architecture.
Choice of technologies
I chose PlanetScale because it’s serverless and MySQL, 2 of my criteria.
To communicate with my PlanetScale database, I chose to use Prisma, a Node.js and TypeScript ORM.
Set up Prisma
I started by adding the Prisma client: npm install prisma @prisma/client.
After this install, I added my Prisma schema to my codebase:
Then it got a bit tricky.
Because I’m deploying my blog platform on Vercel’s Edge network, the connections from the platform to the database can not have a persistent connection.
After some research, I found out Prisma offers a service to set up connection pooling called Prisma Data Platform.
Once I had created an account on the Data Platform, I was able to create a Data Proxy, which provided me with a connection string to use in my application.
This connection string is what I needed to put in the DATABASE_URL environment variable (which is used in the prisma.schema).
To generate the TypeScript types based on my Prisma schema, I just ran npx prisma generate, this will by default generate the types in the node_modules folder in your project locally.
Setting up PlanetScale
Syncing the schema from Prisma to PlanetScale is as easy as running npx prisma db push in your terminal.
To communicate from my frontend to my API routes, I opted to use TanStack Query, my favourite tool to handle client-side API calls in React.
The frontend code to add and list comments for a blog post looks like this (this part I wrote in React):
The code for the API route to create blogs looks like this:
And the code to list the comments for a post looks like this:
Setting up the ‘Edge’ part
Deploying Astro to Vercel Edge is as easy as adding the Astro with Vercel integration and setting up the edge target.
My astro config (note the edge in the import path):
I also had to configure an alias in Vite for the Prisma client to get it working on Vercel combined with Astro.
When building the application on Vercel, we also want to generate the client again to make sure the client is available in the node_modules there too.
In the package.json I use "build": "prisma generate --data-proxy && astro build" for this.
Instantiating the Prisma client in the code is done in lib/prisma-client.ts.
I used lazy imports from Node.js here to make it work correctly locally and on Vercel.
To make my code run locally too, I needed to change the DATABASE_URL environment variable to make it point directly to PlanetScale instead of going through Prisma Proxy.
Go check it out on my blog, and add a comment ;-).
Source code can be found on my Github.
Did you like this post? Check out my latest blog posts: