/ Home / Blog

Adding Prisma to Next.js API Routes on Amplify Hosting

June 21, 2022

This is a quick follow to Deploying Next.js SSR and Prisma on Amplify Hosting.

Once you have Prisma deployed and working with Next.js getServerSideProps, you can extend the database access into the API routes.

Adjust the default hello.js with the below Prisma query. This is the same query as the index.js SSR call in the previous post.

// /api/hello.js
import prisma from "@/lib/prisma";

export default async function handler(req, res) {
  const posts = await prisma.post.findMany({
    select: {
      id: true,
      title: true,
      description: true,
    },
  });

  res.status(200).json({ posts });
}

The response, if using the seed data will look similar:

// api response
{
  "posts": [
    {
      "id": "cl4ob7ktz00007mupv3jaduyu",
      "title": "First post",
      "description": "Lorem ipsum dolor sit amet"
    },
    {
      "id": "cl4ob7ku100017mupoh1dvigw",
      "title": "Second post",
      "description": "Ipsum dolor sit amet"
    }
  ]
}

Also, if you’d like to configure module aliases, add the below in a new jsconfig.json.

```diff
  .
  ├── node_modules/
  ├── lib/
  ├── prisma/
  ├── pages/
  ├── public/
  ├── styles/
  ├── next.config.js 
  ├── .env
+ ├── jsconfig.json
  ...

  └─ README.md

The below setup will allow Prisma to be imported using import prisma from "@/lib/prisma"; with the @ alias.

// jsconfig.json
{
    "compilerOptions": {
      "baseUrl": ".",
      "paths": {
        "@/components/*": ["components/*"],
        "@/lib/*": ["lib/*"],
        "@/styles/*": ["styles/*"]
      }
    }
  }

Add just like that you can now power API routes using Prisma. You can add additional Server Side business logic and call additional external APIs, if needed.

Also, this can be redeployed in the previous app to run on Amplify Hosting 🚀.

👋 Related posts in the 100 Days of AWS Amplify series...