Building a simple blog application with EdgeDB and Next.js

We’re going to build a simple blog application with Next.js and EdgeDB. Let’s start by scaffolding out app with Next.js’s create-next-app tool. We’ll be using TypeScript for this tutorial.

  1. $
  1. npx create-next-app --typescript nextjs-todo

This will take a minute to run. The scaffolding tool is creating a simple Next.js app and installing all our dependencies for us. Once it’s complete, let’s navigate into the directory and start the dev server.

  1. $
  1. cd nextjs-blog
  1. $
  1. yarn dev

Open localhost:3000 to see the default Next.js homepage. At this point the app’s file structure looks like this:

  1. README.md
  2. tsconfig.json
  3. package.json
  4. next.config.js
  5. next-env.d.ts
  6. pages
  7. ├── _app.tsx
  8. ├── api
  9. └── hello.ts
  10. └── index.tsx
  11. public
  12. ├── favicon.ico
  13. └── vercel.svg
  14. styles
  15. ├── Home.module.css
  16. └── globals.css

There’s a custom App component defined in pages/_app.tsx that loads some global CSS, plus the homepage at pages/index.tsx and a single API route at pages/api/hello.ts. The styles and public directories contain some other assets.

Updating the homepage

Let’s start by implementing a simple homepage for our blog application using static data. Replace the contents of pages/index.tsx with the following.

  1. // pages/index.tsx
  2. import type {NextPage} from 'next';
  3. import Head from 'next/head';
  4. import styles from '../styles/Home.module.css';
  5. type Post = {
  6. id: string;
  7. title: string;
  8. content: string;
  9. };
  10. const HomePage: NextPage = () => {
  11. const posts: Post[] = [
  12. {
  13. id: 'post1',
  14. title: 'This one weird trick makes using databases fun',
  15. content: 'Use EdgeDB',
  16. },
  17. {
  18. id: 'post2',
  19. title: 'How to build a blog with EdgeDB and Next.js',
  20. content: "Let's start by scaffolding out app with `create-next-app`.",
  21. },
  22. ];
  23. return (
  24. <div className={styles.container}>
  25. <Head>
  26. <title>My Blog</title>
  27. <meta name="description" content="An awesome blog" />
  28. <link rel="icon" href="/favicon.ico" />
  29. </Head>
  30. <main className={styles.main}>
  31. <h1 className={styles.title}>Blog</h1>
  32. <div style={{height: '50px'}}></div>
  33. {posts.map((post) => {
  34. return (
  35. <a href={`/post/${post.id}`} key={post.id}>
  36. <div className={styles.card}>
  37. <p>{post.title}</p>
  38. </div>
  39. </a>
  40. );
  41. })}
  42. </main>
  43. </div>
  44. );
  45. };
  46. export default HomePage;

After saving, Next.js should hot-reload, and the homepage should look something like this.

Next.js - 图1

Initializing EdgeDB

Now let’s spin up a database for the app. First, install the edgedb CLI.

Linux or macOS

  1. $
  1. curl --proto '=https' --tlsv1.2 -sSf https://sh.edgedb.com | sh

Windows Powershell

  1. PS>
  1. iwr https://ps1.edgedb.com -useb | iex

Then check that the CLI is available with the edgedb --version command. If you get a Command not found error, you may need to open a new terminal window before the edgedb command is available.

Once the CLI is installed, initialize a project from the application’s root directory. You’ll be presented with a series of prompts.

  1. $
  1. edgedb project init
  1. No `edgedb.toml` found in `~/nextjs-blog` or above
  2. Do you want to initialize a new project? [Y/n]
  3. > Y
  4. Specify the name of EdgeDB instance to use with this project [default:
  5. nextjs-blog]:
  6. > nextjs-blog
  7. Checking EdgeDB versions...
  8. Specify the version of EdgeDB to use with this project [default: 1.x]:
  9. > 1.x
  10. Do you want to start instance automatically on login? [y/n]
  11. > y
  12. ┌─────────────────────┬──────────────────────────────────────────────┐
  13. Project directory ~/nextjs-blog
  14. Project config ~/nextjs-blog/edgedb.toml
  15. Schema dir (empty) ~/nextjs-blog/dbschema
  16. Installation method portable package
  17. Start configuration manual
  18. Version 1.x
  19. Instance name nextjs-blog
  20. └─────────────────────┴──────────────────────────────────────────────┘
  21. Initializing EdgeDB instance...
  22. Applying migrations...
  23. Everything is up to date. Revision initial.
  24. Project initialized.

This process has spun up an EdgeDB instance called nextjs-blog and “linked” it with your current directory. As long as you’re inside that directory, CLI commands and client libraries will be able to connect to the linked instance automatically, without additional configuration.

To test this, run the edgedb command to open a REPL to the linked instance.

  1. $
  1. edgedb
  1. EdgeDB 1.x (repl 1.x)
  2. Type \help for help, \quit to quit.
  3. edgedb> select 2 + 2;
  4. {4}
  5. >

From inside this REPL, we can execute EdgeQL queries against our database. But there’s not much we can do currently, since our database is schemaless. Let’s change that.

The project initialization process also created a new subdirectory in our project called dbschema. This is folder that contains everything pertaining to EdgeDB. Currently it looks like this:

  1. dbschema
  2. ├── default.esdl
  3. └── migrations

The default.esdl file will contain our schema. The migrations directory is currently empty, but will contain our migration files. Let’s update the contents of default.esdl with the following simple blog schema.

  1. # dbschema/default.esdl
  2. module default {
  3. type BlogPost {
  4. required property title -> str;
  5. required property content -> str {
  6. default := ""
  7. };
  8. }
  9. }

EdgeDB let’s you split up your schema into different modules but it’s common to keep your entire schema in the default module.

Save the file, then let’s create our first migration.

  1. $
  1. edgedb migration create
  1. did you create object type 'default::BlogPost'? [y,n,l,c,b,s,q,?]
  2. > y
  3. Created ./dbschema/migrations/00001.edgeql

The dbschema/migrations now contains a migration file called 00001.edgeql. Currently though, we haven’t applied this migration against our database. Let’s do that.

  1. $
  1. edgedb migrate
  1. Applied m1fee6oypqpjrreleos5hmivgfqg6zfkgbrowx7sw5jvnicm73hqdq (00001.edgeql)

Our database now has a schema consisting of the BlogPost type. We can create some sample data from the REPL. Run the edgedb command to re-open the REPL.

  1. $
  1. edgedb
  1. EdgeDB 1.x (repl 1.x)
  2. Type \help for help, \quit to quit.
  3. edgedb>

Then execute the following insert statements.

  1. edgedb>
  2. .......
  3. .......
  4. .......
  1. insert BlogPost {
  2. title := "This one weird trick makes using databases fun",
  3. content := "Use EdgeDB"
  4. };
  1. {default::BlogPost {id: 7f301d02-c780-11ec-8a1a-a34776e884a0}}
  1. edgedb>
  2. .......
  3. .......
  4. .......
  1. insert BlogPost {
  2. title := "How to build a blog with EdgeDB and Next.js",
  3. content := "Let's start by scaffolding our app..."
  4. };
  1. {default::BlogPost {id: 88c800e6-c780-11ec-8a1a-b3a3020189dd}}

Loading posts with an API route

Now that we have a couple posts in the database, let’s load them dynamically with a Next.js API route. To do that, we’ll need the edgedb client library. Let’s install that from NPM:

  1. $
  1. npm install edgedb

Then create a new file at pages/api/post.ts and copy in the following code.

  1. // pages/api/post.ts
  2. import type {NextApiRequest, NextApiResponse} from 'next';
  3. import {createClient} from 'edgedb';
  4. export const client = createClient();
  5. export default async function handler(
  6. req: NextApiRequest,
  7. res: NextApiResponse
  8. ) {
  9. const posts = await client.query(`select BlogPost {
  10. id,
  11. title,
  12. content
  13. };`);
  14. res.status(200).json(posts);
  15. }

This file initializes an EdgeDB client, which manages a pool of connections to the database and provides an API for executing queries. We’re using the .query() method to fetch all the posts in the database with a simple select statement.

If you visit localhost:3000/api/post in your browser, you should be a plaintext JSON representation of the blog posts we inserted earlier.

To fetch these from the homepage, we’ll use useState, useEffect, and the built-in fetch API. At the top of the HomePage component in pages/index.tsx, replace the static data and add the missing imports.

  1. // pages/index.tsx
  2. import {useState, useEffect} from 'react';
  3. type Post = {
  4. id: string;
  5. title: string;
  6. content: string;
  7. };
  8. const HomePage: NextPage = () => {
  9. const posts: Post[] = [
  10. {
  11. id: 'post1',
  12. title: 'This one weird trick makes using databases fun',
  13. content: 'Use EdgeDB',
  14. },
  15. {
  16. id: 'post2',
  17. title: 'How to build a blog with EdgeDB and Next.js',
  18. content: "Let's start by scaffolding our app...",
  19. },
  20. ];
  21. const [posts, setPosts] = useState<Post[] | null>(null);
  22. useEffect(() => {
  23. fetch(`/api/post`)
  24. .then((result) => result.json())
  25. .then(setPosts);
  26. }, []);
  27. if (!posts) return <p>Loading...</p>;
  28. return <div>...</div>;
  29. }

When you refresh the page, you should briefly see a Loading... indicator before the homepage renders the (dynamically loaded!) blog posts.

Generating the query builder

Since we’re using TypeScript, it makes sense to use EdgeDB’s powerful query builder. This provides a schema-aware client API that makes writing strongly typed EdgeQL queries easy and painless. The result type of our queries will be automatically inferred, so we won’t need to manually type something like type Post = { id: string; ... }.

Generate the query builder with the following command.

  1. $
  1. npx edgeql-js
  1. Detected tsconfig.json, generating TypeScript files.
  2. To override this, use the --target flag.
  3. Run `npx edgeql-js --help` for details.
  4. Generating query builder into ./dbschema/edgeql-js
  5. Connecting to EdgeDB instance...
  6. Introspecting database schema...
  7. Generation successful!
  8. Checking the generated query builder into version control
  9. is NOT RECOMMENDED. Would you like to update .gitignore to ignore
  10. the query builder directory? The following line will be added:
  11. dbschema/edgeql-js
  12. [y/n] (leave blank for "y")
  13. > y

This command introspected the schema of our database and generated some code into the dbschema/edgeql-js directory. It also asked us if wanted to add the generated code to our .gitignore; typically it’s not good practice to include generated files in version control.

Back in pages/api/post.ts, let’s update our code to use the query builder instead.

  1. // pages/api/post.ts
  2. import type {NextApiRequest, NextApiResponse} from 'next';
  3. import {createClient} from 'edgedb';
  4. import e, {$infer} from '../../dbschema/edgeql-js';
  5. export const client = createClient();
  6. const selectPosts = e.select(e.BlogPost, () => ({
  7. id: true,
  8. title: true,
  9. content: true,
  10. }));
  11. export type Posts = $infer<typeof selectPosts>;
  12. export default async function handler(
  13. req: NextApiRequest,
  14. res: NextApiResponse
  15. ) {
  16. const posts = await client.query(`select BlogPost {
  17. id,
  18. title,
  19. content
  20. };`);
  21. const posts = await selectPosts.run(client);
  22. res.status(200).json(posts);
  23. }

Instead of writing our query as a plain string, we’re now using the query builder to declare our query in a code-first way. As you can see we import the query builder as a single default import e from the dbschema/edgeql-js directory.

We’re also using a utility called $infer to extract the inferred type of this query. In VSCode you can hover over Posts to see what this type is.

Next.js - 图2

Back in pages/index.tsx, lets update our code to use the inferred Posts type instead of our manual type declaration.

  1. // pages/index.tsx
  2. import type {NextPage} from 'next';
  3. import Head from 'next/head';
  4. import {useEffect, useState} from 'react';
  5. import styles from '../styles/Home.module.css';
  6. import {Posts} from "./api/post";
  7. type Post = {
  8. id: string;
  9. title: string;
  10. content: string;
  11. };
  12. const Home: NextPage = () => {
  13. const [posts, setPosts] = useState<Posts | null>(null);
  14. // ...
  15. }

Now, when we update our selectPosts query, the type of our dynamically loaded posts variable will update automatically—no need to keep our type definitions in sync with our API logic!

Rendering blog posts

Our homepage renders a list of links to each of our blog posts, but we haven’t implemented the page that actually displays the posts. Let’s create a new page at pages/post/[id].tsx. This is a dynamic route that includes an id URL parameter. We’ll use this parameter to fetch the appropriate post from the database.

Create pages/post/[id].tsx and add the following code. We’re using getServerSideProps to load the blog post data server-side, to avoid loading spinners and ensure the page loads fast.

  1. import React from 'react';
  2. import {GetServerSidePropsContext, InferGetServerSidePropsType} from 'next';
  3. import {client} from '../api/post';
  4. import e from '../../dbschema/edgeql-js';
  5. export const getServerSideProps = async (
  6. context?: GetServerSidePropsContext
  7. ) => {
  8. const post = await e
  9. .select(e.BlogPost, (post) => ({
  10. id: true,
  11. title: true,
  12. content: true,
  13. filter: e.op(post.id, '=', e.uuid(context!.params!.id as string)),
  14. }))
  15. .run(client);
  16. return {props: {post: post!}};
  17. };
  18. export type GetPost = InferGetServerSidePropsType<typeof getServerSideProps>;
  19. const Post: React.FC<GetPost> = (props) => {
  20. return (
  21. <div
  22. style={{
  23. margin: 'auto',
  24. width: '100%',
  25. maxWidth: '600px',
  26. }}
  27. >
  28. <h1 style={{padding: '50px 0px'}}>{props.post.title}</h1>
  29. <p style={{color: '#666'}}>{props.post.content}</p>
  30. </div>
  31. );
  32. };
  33. export default Post;

Inside getServerSideProps we’re extracting the id parameter from context.params and using it in our EdgeQL query. The query is a select query that fetches the id, title, and content of the post with a matching id.

We’re using Next’s InferGetServerSidePropsType utility to extract the inferred type of our query and pass it into React.FC. Now, if we update our query, the type of the component props will automatically update too. In fact, this entire application is end-to-end typesafe.

Now, click on one of the blog post links on the homepage. This should bring you to /post/<uuid>, which should display something like this:

Next.js - 图3

Deploying to Vercel

#1 Deploy EdgeDB

First deploy an EdgeDB instance on your preferred cloud provider:

#2. Find your instance’s DSN

The DSN is also known as a connection string. It will have the format edgedb://username:password@hostname:port. The exact instructions for this depend on which cloud you are deploying to.

#3 Apply migrations

Use the DSN to apply migrations against your remote instance.

  1. $
  1. edgedb migrate --dsn <your-instance-dsn> --tls-security insecure

You have to disable TLS checks with --tls-security insecure. All EdgeDB instances use TLS by default, but configuring it is out of scope of this project.

Once you’ve applied the migrations, consider creating some sample data in your

database. Open a REPL and insert some blog posts:

  1. $
  1. edgedb --dsn <your-instance-dsn> --tls-security insecure
  1. EdgeDB 1.x (repl 1.x)
  2. Type \help for help, \quit to quit.
  3. edgedb> insert BlogPost { title := "Test post" };
  4. {default::BlogPost {id: c00f2c9a-cbf5-11ec-8ecb-4f8e702e5789}}

#4 Set up a `prebuild` script

Add the following prebuild script to your package.json. When Vercel initializes the build, it will trigger this script which will generate the query builder. The npx edgeql-js command will read the value of the EDGEDB_DSN variable, connect to the database, and generate the query builder before Vercel starts building the project.

  1. // package.json
  2. "scripts": {
  3. "dev": "next dev",
  4. "build": "next build",
  5. "start": "next start",
  6. "lint": "next lint",
  7. "prebuild": "npx edgeql-js"
  8. },

#5 Deploy to Vercel

Deploy this app to Vercel with the button below.

Next.js - 图4

When prompted:

  • Set EDGEDB_DSN to your database’s DSN

  • Set EDGEDB_CLIENT_TLS_SECURITY to insecure. This will disable EdgeDB’s default TLS checks; configuring TLS is beyond the scope of this tutorial.

Next.js - 图5

#6 View the application

Once deployment has completed, view the application at the deployment URL supplied by Vercel.

Wrapping up

Admittedly this isn’t the prettiest blog of all time, or the most feature-complete. But this tutorial demonstrates how to work with EdgeDB in a Next.js app, including data fetching with API routes and getServerSideProps.

The next step is to add a /newpost page with a form for writing new blog posts and saving them into EdgeDB. That’s left as an exercise for the reader.

To see the final code for this tutorial, refer to github.com/edgedb/edgedb-examples/tree/main/nextjs-blog.