Skip to content

Files

Latest commit

 

History

History

nextjs-graphql

Fullstack Example with Next.js (GraphQL API)

This example shows how to implement a Fullstack Next.js app with GraphQL with the following stack:

This example shows how to implement a **fullstack app in TypeScript with :

Getting started

1. Download example and navigate into the project directory

Download this example:

npx try-prisma@latest --template orm/nextjs-graphql

Then, navigate into the project directory:

cd nextjs-graphql
Alternative: Clone the entire repo

Clone this repository:

git clone git@github.com:prisma/prisma-examples.git --depth=1

Install npm dependencies:

cd prisma-examples/orm/nextjs-graphql
npm install

[Optional] Switch database to Prisma Postgres

This example uses a local SQLite database by default. If you want to use to Prisma Postgres, follow these instructions (otherwise, skip to the next step):

  1. Set up a new Prisma Postgres instance in the Prisma Data Platform Console and copy the database connection URL.

  2. Update the datasource block to use postgresql as the provider and paste the database connection URL as the value for url:

    datasource db {
      provider = "postgresql"
      url      = "prisma+postgres://accelerate.prisma-data.net/?api_key=ey...."
    }

    Note: In production environments, we recommend that you set your connection URL via an environment variable, e.g. using a .env file.

  3. Install the Prisma Accelerate extension:

    npm install @prisma/extension-accelerate
    
  4. Add the Accelerate extension to the PrismaClient instance:

    + import { withAccelerate } from "@prisma/extension-accelerate"
    
    + const prisma = new PrismaClient().$extends(withAccelerate())

That's it, your project is now configured to use Prisma Postgres!

2. Create and seed the database

Run the following command to create your database. This also creates the User and Post tables that are defined in prisma/schema.prisma:

npx prisma migrate dev --name init

When npx prisma migrate dev is executed against a newly created database, seeding is also triggered. The seed file in prisma/seed.ts will be executed and your database will be populated with the sample data.

If you switched to Prisma Postgres in the previous step, you need to trigger seeding manually (because Prisma Postgres already created an empty database instance for you, so seeding isn't triggered):

npx prisma db seed

2. Start the app

npm run dev

The app is now running, navigate to http://localhost:3000/ in your browser to explore its UI.

Expand for a tour through the UI of the app

Blog (located in ./pages/index.tsx)

Signup (located in ./pages/signup.tsx)

Create post (draft) (located in ./pages/create.tsx)

Drafts (located in ./pages/drafts.tsx)

View post (located in ./pages/p/[id].tsx) (delete or publish here)

Using the GraphQL API

You can also access the GraphQL API of the API server directly. It is running on the same host machine and port and can be accessed via the /api route (in this case that is localhost:3000/api).

Below are a number of operations that you can send to the API.

Retrieve all published posts and their authors

query {
  feed {
    id
    title
    content
    published
    author {
      id
      name
      email
    }
  }
}
See more API operations

Create a new user

mutation {
  signupUser(name: "Sarah", email: "sarah@prisma.io") {
    id
  }
}

Create a new draft

mutation {
  createDraft(
    title: "Join the Prisma Discord"
    content: "https://pris.ly/discord"
    authorEmail: "alice@prisma.io"
  ) {
    id
    published
  }
}

Publish an existing draft

mutation {
  publish(postId: "__POST_ID__") {
    id
    published
  }
}

Note: You need to replace the __POST_ID__-placeholder with an actual id from a Post item. You can find one e.g. using the filterPosts-query.

Search for posts with a specific title or content

{
  filterPosts(searchString: "graphql") {
    id
    title
    content
    published
    author {
      id
      name
      email
    }
  }
}

Retrieve a single post

{
  post(postId: "__POST_ID__") {
    id
    title
    content
    published
    author {
      id
      name
      email
    }
  }
}

Note: You need to replace the __POST_ID__-placeholder with an actual id from a Post item. You can find one e.g. using the filterPosts-query.

Delete a post

mutation {
  deletePost(postId: "__POST_ID__") {
    id
  }
}

Note: You need to replace the __POST_ID__-placeholder with an actual id from a Post item. You can find one e.g. using the filterPosts-query.

Evolving the app

Evolving the application typically requires three steps:

  1. Migrate your database using Prisma Migrate
  2. Update your server-side application code
  3. Build new UI features in React

For the following example scenario, assume you want to add a "profile" feature to the app where users can create a profile and write a short bio about themselves.

1. Migrate your database using Prisma Migrate

The first step is to add a new table, e.g. called Profile, to the database. You can do this by adding a new model to your Prisma schema file file and then running a migration afterwards:

// ./prisma/schema.prisma

model User {
  id      Int      @default(autoincrement()) @id
  name    String?
  email   String   @unique
  posts   Post[]
+ profile Profile?
}

model Post {
  id        Int      @id @default(autoincrement())
  title     String
  content   String?
  published Boolean  @default(false)
  author    User?    @relation(fields: [authorId], references: [id])
  authorId  Int?
}

+model Profile {
+  id     Int     @default(autoincrement()) @id
+  bio    String?
+  user   User    @relation(fields: [userId], references: [id])
+  userId Int     @unique
+}

Once you've updated your data model, you can execute the changes against your database with the following command:

npx prisma migrate dev --name add-profile

This adds another migration to the prisma/migrations directory and creates the new Profile table in the database.

2. Update your application code

You can now use your PrismaClient instance to perform operations against the new Profile table. Those operations can be used to implement queries and mutations in the GraphQL API.

2.1. Add the Profile type to your GraphQL schema

First, add a new GraphQL type via Pothos's prismaObject function:

// ./pages/api/graphql.ts

+builder.prismaObject('Profile', {
+  fields: (t) => ({
+    id: t.exposeInt('id'),
+    bio: t.exposeString('bio', { nullable: true }),
+    user: t.relation('user'),
+  }),
+})

builder.prismaObject('User', {
  fields: (t) => ({
    id: t.exposeInt('id'),
    name: t.exposeString('name', { nullable: true }),
    email: t.exposeString('email'),
    posts: t.relation('posts'),
+    profile: t.relation('profile'),
  }),
})

2.2. Add a createProfile GraphQL mutation

// ./pages/api/graphql.ts

// other object types, queries and mutations


+builder.mutationField('createProfile', (t) =>
+  t.prismaField({
+    type: 'Profile',
+    args: {
+      bio: t.arg.string({ required: true }),
+      data: t.arg({ type: UserUniqueInput })
+    },
+    resolve: async (query, _parent, args, _context) =>
+      prisma.profile.create({
+        ...query,
+        data: {
+          bio: args.bio,
+          user: {
+            connect: {
+              id: args.data?.id || undefined,
+              email: args.data?.email || undefined
+            }
+          }
+        }
+      })
+  })
+)

Finally, you can test the new mutation like this:

mutation {
  createProfile(
    email: "mahmoud@prisma.io"
    bio: "I like turtles"
  ) {
    id
    bio
    user {
      id
      name
    }
  }
}
Expand to view more sample Prisma Client queries on Profile

Here are some more sample Prisma Client queries on the new Profile model:

Create a new profile for an existing user
const profile = await prisma.profile.create({
  data: {
    bio: 'Hello World',
    user: {
      connect: { email: 'alice@prisma.io' },
    },
  },
})
Create a new user with a new profile
const user = await prisma.user.create({
  data: {
    email: 'john@prisma.io',
    name: 'John',
    profile: {
      create: {
        bio: 'Hello World',
      },
    },
  },
})
Update the profile of an existing user
const userWithUpdatedProfile = await prisma.user.update({
  where: { email: 'alice@prisma.io' },
  data: {
    profile: {
      update: {
        bio: 'Hello Friends',
      },
    },
  },
})

3. Build new UI features in React

Once you have added a new query or mutation to the API, you can start building a new UI component in React. It could e.g. be called profile.tsx and would be located in the pages directory.

In the application code, you can access the new operations via Apollo Client and populate the UI with the data you receive from the API calls.

Next steps