Design Converter
Education
Software Development Executive - I
Last updated on Oct 18, 2024
Last updated on Oct 18, 2024
In web development, the quest for efficiency, scalability, and robustness in full-stack applications is never-ending. The combination of Next.js, GraphQL, TypeScript, Prisma, and Vercel offers a powerful stack for developers aiming to build cutting-edge applications.
In this article, we will learn how to build a simple GraphQL server using Next.js, Prisma, and TypeScript. We will cover the basics of GraphQL, Prisma, and Next.js, and how to integrate them to create a full-stack application. By the end of this tutorial, you will have a solid understanding of how to set up a GraphQL server, define a Prisma schema, and fetch data using GraphQL queries within a Next.js framework.
To follow along with this article, you need to have basic knowledge of JavaScript, React, and Node.js. Familiarity with Next.js, Prisma, and TypeScript is also essential. Ensure you have these tools installed on your machine to get started. If you haven’t already, you can install Next.js by running npx create-next-app
, Prisma by running npm install prisma @prisma/client
, and TypeScript by running npm install typescript
.
To set up environment variables, create a new file named .env
in the root of your project. In this file, add the following variables:
1DATABASE_URL="postgresql://username:password@host:port/database" 2NEXT_PUBLIC_API_URL="http://localhost:3000/api"
Replace the username
, password
, host
, port
, and database
placeholders with your actual PostgreSQL database credentials.
The DATABASE_URL
variable is crucial for connecting Prisma to your PostgreSQL database, while NEXT_PUBLIC_API_URL
ensures your Next.js application can access the GraphQL API. This setup is essential for a smooth development experience, allowing your application to fetch data and interact with the database seamlessly.
Kickstart your project by running the npx create-next-app my-app
command in your terminal. This command scaffolds a new Next.js project, setting the stage for our full-stack application.
Next, install the necessary dependencies by executing the following command:
1npm install prisma graphql @prisma/client
These packages are essential for integrating GraphQL and Prisma into your Next.js application, providing the tools needed to define your database schema and GraphQL API.
The heart of your application's data model lies within the Prisma schema. Begin by creating a new file named prisma/schema.prisma
. Here, define your database schema using the Prisma Schema Language (PSL), which allows for clear and concise modeling of your data. For instance:
1datasource db { 2 provider = "postgresql" 3 url = env("DATABASE_URL") 4} 5 6model User { 7 id Int @id @default(autoincrement()) 8 email String @unique 9 name String 10}
This schema defines a simple User
model as an example. Don't forget to configure your database connection URL in the .env
file to connect to your PostgreSQL database.
With your schema defined, generate the Prisma client by running the following command:
1npx prisma generate
This command creates a type-safe query builder that you’ll use to interact with your database, ensuring your data access is both efficient and error-free.
Designing your data model is a critical step in building your application. Prisma’s Schema Language makes this process intuitive and straightforward. After defining your models, use the following command to apply your database migrations:
1npx prisma migrate dev
To add sample data to your database, utilize Prisma Studio by running:
1npx prisma studio
This graphical interface lets you easily insert and manage data, providing a visual representation of your database schema.
Integrating a GraphQL server into your Next.js application involves creating a schema that defines your API's data types and operations. In a graphql/schema.ts
file, use the gql
template literal to define your schema, like so:
1import { gql } from 'apollo-server-micro'; 2 3export const typeDefs = gql` 4 type Query { 5 users: [User!]! 6 } 7 8 type User { 9 id: ID! 10 name: String! 11 email: String! 12 } 13`;
This schema outlines a simple query that fetches users from your database.
Resolvers are functions that handle the logic for fetching the data for your GraphQL operations. In a graphql/resolvers.ts
file, implement these functions, utilizing the Prisma client to interact with your database:
1import { PrismaClient } from '@prisma/client'; 2const prisma = new PrismaClient(); 3 4export const resolvers = { 5 Query: { 6 users: async () => await prisma.user.findMany(), 7 }, 8};
Setting up Apollo Server in your Next.js application is straightforward. Create a new file under pages/api/graphql.ts
and configure your Apollo Server to use the schema and resolvers you've defined:
1import { ApolloServer } from 'apollo-server-micro'; 2import { typeDefs } from '../../graphql/schema'; 3import { resolvers } from '../../graphql/resolvers'; 4 5const apolloServer = new ApolloServer({ typeDefs, resolvers }); 6export const config = { 7 api: { 8 bodyParser: false, 9 }, 10}; 11 12export default apolloServer.createHandler({ path: '/api/graphql' });
This setup enables your Next.js application to handle GraphQL requests, making your API accessible at /api/graphql
.
Creating a React component to display user data involves fetching data from your GraphQL API using a GraphQL client like Apollo Client. Implement a UserList
component that queries the API and displays the results:
1import { useQuery, gql } from '@apollo/client'; 2 3const USERS_QUERY = gql` 4 query Users { 5 users { 6 id 7 name 8 email 9 } 10 } 11`; 12 13export default function UserList() { 14 const { data, loading, error } = useQuery(USERS_QUERY); 15 16 if (loading) return <p>Loading...</p>; 17 if (error) return <p>Error: {error.message}</p>; 18 19 return ( 20 <ul> 21 {data.users.map((user) => ( 22 <li key={user.id}> 23 {user.name} - {user.email} 24 </li> 25 ))} 26 </ul> 27 ); 28}
Building a full-stack application with Next.js, GraphQL, TypeScript, Prisma, and Vercel offers a modern, efficient, and scalable approach to web development. By following the steps outlined in this tutorial, you've learned how to set up your project, model data with Prisma, implement a GraphQL API, and create a frontend interface to interact with your API. Remember to adhere to best practices for security, performance, and scalability to ensure your application is robust and reliable.
Tired of manually designing screens, coding on weekends, and technical debt? Let DhiWise handle it for you!
You can build an e-commerce store, healthcare app, portfolio, blogging website, social media or admin panel right away. Use our library of 40+ pre-built free templates to create your first application using DhiWise.