Build API-Only Projects with Next.js, Prisma, and Supabase

Creating an API-only project in Next.js offers the flexibility to leverage the Next.js file-based routing system, API routes, and powerful integrations such as Prisma and Supabase. This setup will allow you to manage your database, interact with it via Prisma, and handle authentication and data with Supabase Postgres.

  1. Prerequisites
  2. Setting up the Project
  3. Installing Dependencies
  4. Configuring Supabase
  5. Setting up Prisma
  6. Creating API Routes in Next.js
  7. Deploying the API
  8. Conclusion

Prerequisites

Before starting, make sure you have the necessary installed:

  • Node.js (v16+)
  • Supabase Account (for database hosting)
  • Postgres Database (via Supabase)
  • Prisma ORM

Familiarity with Next.js, Prisma, and Supabase will also help.

Setting up the Project

First, set up a new Next.js project.

npx create-next-app@latest my-api-project
cd my-api-project

Since this is an API-only project, you can safely remove the default pages/index.tsx and pages/api/hello.ts files. We’ll focus on building our API inside the pages/api directory.

Installing Dependencies

Now, install the necessary dependencies for Prisma and Supabase:

npm install @prisma/client prisma @supabase/supabase-js
  • @prisma/client: The Prisma client to query the database.
  • prisma: The Prisma toolkit for schema migrations.
  • @supabase/supabase-js: Supabase JavaScript SDK for interacting with the Supabase database.

Configuring Supabase

  1. Create a New Supabase Project: Go to the Supabase dashboard and create a new project. Note down the API link, public anon key, and the database connection string from the Settings > API section.
  2. Set Up Environment Variables: In your Next.js project, create an .env.local file to store sensitive information like the database URL and Supabase keys.
NEXT_PUBLIC_SUPABASE_URL=https://xyzcompany.supabase.co
NEXT_PUBLIC_SUPABASE_ANON_KEY=your-anon-key
DATABASE_URL=postgresql://username:password@dbhost:5432/mydb
  • NEXT_PUBLIC_SUPABASE_URL: URL for your Supabase project.
  • NEXT_PUBLIC_SUPABASE_ANON_KEY: The public anonymous key for accessing Supabase from the frontend.
  • DATABASE_URL: The connection string to your Postgres database hosted on Supabase.

Setting up Prisma

  1. Initialize Prisma: Run the following command to initialize Prisma in your project.
npx prisma init

This creates a prisma folder with a schema.prisma file and updates your .env with DATABASE_URL.

  1. Update Schema: Open prisma/schema.prisma and define a model. For example:
datasource db {
  provider = "postgresql"
  url      = env("DATABASE_URL")
}

generator client {
  provider = "prisma-client-js"
}

model User {
  id        Int      @id @default(autoincrement())
  email     String   @unique
  name      String?
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt
}
  1. Migrate the Database: After updating the schema, apply the changes to your Supabase database:
npx prisma migrate dev --name init

This will create a User table in your Supabase Postgres database.

  1. Generate Prisma Client: Run the following command to generate the Prisma client.
npx prisma generate

Creating API Routes in Next.js

Next.js provides a simple way to create APIs using the /pages/api directory. Let’s create a basic CRUD API for the User model.

  1. Creating a User: Inside pages/api/user/index.ts, create a POST endpoint to add a new user.
import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient();

export default async function handler(req, res) {
  if (req.method === 'POST') {
    const { email, name } = req.body;

    try {
      const user = await prisma.user.create({
        data: {
          email,
          name,
        },
      });
      res.status(201).json(user);
    } catch (error) {
      res.status(400).json({ error: 'User creation failed' });
    }
  } else {
    res.status(405).json({ message: 'Method not allowed' });
  }
}
  1. Getting All Users: To fetch all users, add a GET request handler in the same file.
if (req.method === 'GET') {
  try {
    const users = await prisma.user.findMany();
    res.status(200).json(users);
  } catch (error) {
    res.status(400).json({ error: 'Failed to fetch users' });
  }
}

Now you have both POST and GET API endpoints ready for creating and fetching users.

Deploying the API

You can deploy your Next.js API project using Vercel, the creators of Next.js. Simply push your code to a GitHub repository and connect it to Vercel.

  1. Push Code to GitHub:
   git init
   git add .
   git commit -m "Initial commit"
   git remote add origin <YOUR_GITHUB_REPO_URL>
   git push -u origin main
  1. Deploy to Vercel:
  • Sign in to Vercel and import your GitHub repository.
  • Add the necessary environment variables (NEXT_PUBLIC_SUPABASE_URL, NEXT_PUBLIC_SUPABASE_ANON_KEY, and DATABASE_URL).
  • Click deploy, and your API will be live.

Conclusion

In this guide, you learned how to create an API-only project in Next.js with Prisma and Supabase Postgres. This stack provides a powerful yet flexible way to build backends quickly, with an API layer built into the Next.js framework.

You can now extend this API with additional models. You can integrate authentication using Supabase’s built-in auth tools. You can also expand it with more advanced features like pagination and filtering.

Happy Coding!

Understanding Pure Functions in JavaScript

In the world of programming, functions are fundamental building blocks that help developers write organized, reusable, and efficient code. Among various types of functions, pure functions hold a special place, particularly in functional programming paradigms. In this blog post, we’ll delve into the concept of pure functions in JavaScript, explore their characteristics, and understand why they are valuable.

What is a Pure Function?

A pure function in JavaScript is a function that adheres to two key principles:

  1. Deterministic: Given the same input, it will always produce the same output.
  2. No Side Effects: It does not modify any state or data outside its scope. This means it does not alter any variables or data structures outside of the function, nor does it perform any operations such as I/O that could have side effects.

Characteristics of Pure Functions

  1. Deterministic: Pure functions always return the same result for the same set of input values. This predictability makes them easy to test and reason about. Let’s consider an example: function add(a, b) { return a + b; } The add function will always return 5 when called with arguments 2 and 3, no matter how many times you call it.
  2. No Side Effects: Pure functions do not modify any external state or interact with the outside world. They do not change global variables, perform I/O operations, or alter the state of passed-in objects. Here’s an example of a function with side effects: let counter = 0; function increment() { counter++; return counter; } The increment function modifies the external counter variable, making it an impure function. Each call to increment produces different results, depending on the state of counter.
  3. Immutability: Pure functions often work with immutable data. Instead of changing the original data, they return new data. This approach ensures that the original data remains unchanged, preserving its integrity.

Benefits of Pure Functions

  1. Testability: Pure functions are easy to test because they always produce the same output for the same input. You don’t need to set up complex external states or mock dependencies. console.log(add(2, 3)); // 5 console.log(add(2, 3)); // 5
  2. Predictability: Pure functions are predictable and consistent. Their behavior is straightforward, and there are no hidden dependencies or side effects to consider.
  3. Referential Transparency: Pure functions exhibit referential transparency, meaning you can replace a function call with its output value without changing the program’s behavior. This property simplifies reasoning about code and facilitates optimization. const result = add(2, 3); // 5 console.log(result); // 5
  4. Concurrency: Pure functions are inherently thread-safe because they do not rely on shared state or mutable data. This makes them suitable for concurrent and parallel execution.

Pure Functions in Functional Programming

Pure functions are a cornerstone of functional programming, a paradigm that treats computation as the evaluation of mathematical functions. In functional programming, pure functions enable key concepts like higher-order functions, function composition, and declarative programming.

Practical Use Case: Array Manipulation

Let’s look at an example of pure functions in action. Consider an array of numbers, and we want to create a new array with each number doubled:

const numbers = [1, 2, 3, 4, 5];

function double(number) {
  return number * 2;
}

const doubledNumbers = numbers.map(double);

console.log(doubledNumbers); // [2, 4, 6, 8, 10]

In this example:

  • The double function is pure because it returns the same result for the same input and has no side effects.
  • The map method creates a new array by applying the double function to each element of the numbers array, preserving immutability.

Conclusion

Pure functions are a powerful concept in JavaScript and functional programming. By adhering to the principles of determinism and no side effects, pure functions offer predictability, testability, and reliability. Embracing pure functions can lead to cleaner, more maintainable code and unlock the benefits of functional programming.

Understanding and leveraging pure functions in your JavaScript code can elevate your programming skills and improve the quality of your applications. So, next time you write a function, ask yourself: Is it pure?