This example shows how to implement a fullstack app in TypeScript with Next.js using React (frontend), Express and Prisma Client (backend). It uses a SQLite database file with some initial dummy data which you can find at ./prisma/dev.db
.
Download this example:
curl https://codeload.github.com/prisma/prisma-examples/tar.gz/latest | tar -xz --strip=2 prisma-examples-latest/typescript/rest-nextjs-api-routes
Install npm dependencies:
cd rest-nextjs-api-routes
npm install
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/typescript/rest-nextjs-api-routes
npm install
Run the following command to create your SQLite database file. 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.
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)
You can also access the REST 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/
, so you can e.g. reach the API with localhost:3000/api/feed
).
/api/post/:id
: Fetch a single post by itsid
/api/feed
: Fetch all published posts/api/filterPosts?searchString={searchString}
: Filter posts bytitle
orcontent
/api/post
: Create a new post- Body:
title: String
(required): The title of the postcontent: String
(optional): The content of the postauthorEmail: String
(required): The email of the user that creates the post
- Body:
/api/user
: Create a new user- Body:
email: String
(required): The email address of the username: String
(optional): The name of the user
- Body:
/api/publish/:id
: Publish a post by itsid
/api/post/:id
: Delete a post by itsid
Evolving the application typically requires three steps:
- Migrate your database using Prisma Migrate
- Update your server-side application code
- 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.
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:
// schema.prisma
model Post {
id Int @default(autoincrement()) @id
title String
content String?
published Boolean @default(false)
author User? @relation(fields: [authorId], references: [id])
authorId Int
}
model User {
id Int @default(autoincrement()) @id
name String?
email String @unique
posts Post[]
+ profile Profile?
}
+model Profile {
+ id Int @default(autoincrement()) @id
+ bio String?
+ userId Int @unique
+ user User @relation(fields: [userId], references: [id])
+}
Once you've updated your data model, you can execute the changes against your database with the following command:
npx prisma migrate dev
You can now use your PrismaClient
instance to perform operations against the new Profile
table. Here are some examples:
const profile = await prisma.profile.create({
data: {
bio: "Hello World",
user: {
connect: { email: "alice@prisma.io" },
},
},
});
const user = await prisma.user.create({
data: {
email: "john@prisma.io",
name: "John",
profile: {
create: {
bio: "Hello World",
},
},
},
});
const userWithUpdatedProfile = await prisma.user.update({
where: { email: "alice@prisma.io" },
data: {
profile: {
update: {
bio: "Hello Friends",
},
},
},
});
Once you have added a new endpoint to the API (e.g. /api/profile
with /POST
, /PUT
and GET
operations), 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 endpoint via fetch
operations and populate the UI with the data you receive from the API calls.
If you want to try this example with another database than SQLite, you can adjust the the database connection in prisma/schema.prisma
by reconfiguring the datasource
block.
Learn more about the different connection configurations in the docs.
Expand for an overview of example configurations with different databases
For PostgreSQL, the connection URL has the following structure:
datasource db {
provider = "postgresql"
url = "postgresql://USER:PASSWORD@HOST:PORT/DATABASE?schema=SCHEMA"
}
Here is an example connection string with a local PostgreSQL database:
datasource db {
provider = "postgresql"
url = "postgresql://janedoe:mypassword@localhost:5432/notesapi?schema=public"
}
For MySQL, the connection URL has the following structure:
datasource db {
provider = "mysql"
url = "mysql://USER:PASSWORD@HOST:PORT/DATABASE"
}
Here is an example connection string with a local MySQL database:
datasource db {
provider = "mysql"
url = "mysql://janedoe:mypassword@localhost:3306/notesapi"
}
Here is an example connection string with a local Microsoft SQL Server database:
datasource db {
provider = "sqlserver"
url = "sqlserver://localhost:1433;initial catalog=sample;user=sa;password=mypassword;"
}
Here is an example connection string with a local MongoDB database:
datasource db {
provider = "mongodb"
url = "mongodb://USERNAME:PASSWORD@HOST/DATABASE?authSource=admin&retryWrites=true&w=majority"
}
Because MongoDB is currently in Preview, you need to specify the previewFeatures
on your generator
block:
generator client {
provider = "prisma-client-js"
previewFeatures = ["mongodb"]
}
- Check out the Prisma docs
- Share your feedback in the
prisma2
channel on the Prisma Slack - Create issues and ask questions on GitHub
- Watch our biweekly "What's new in Prisma" livestreams on Youtube