DEV Community

nabettu
nabettu

Posted on

2

Cost-effective architecture: Using Firestore in Next.js APIs on Cloudflare Pages & Workers.

Hello, I’m watanabe.

Recently, the rising costs of hosting Next.js applications on Vercel have prompted many to seek alternative solutions.

While converting applications to static site SPAs is one approach, it introduces challenges such as setting individual OGP images and managing APIs.

Using Firebase App Hosting or Cloud Run is another alternative, but these services can become costly as access increases, posing challenges for those on a budget.

This has led to growing interest in hosting Next.js applications using Cloudflare Pages and Workers. However, a significant challenge arises: the Firebase Admin SDK relies on Node.js’s internal libraries, which are unavailable in Edge runtime environments like Cloudflare Workers or Vercel Edge Functions. This limitation hinders the use of Firebase services in such environments.

Addressing this issue could enable the use of Firebase’s comprehensive services, such as Authentication and Firestore, without incurring substantial hosting fees.

※It’s worth noting that while Firestore costs can escalate with high read volumes, implementing caching strategies via APIs can mitigate these expenses. However, utilizing Firestore through APIs necessitates REST API access.

Challenges of Firebase Authentication in Edge Runtime Environments

Firebase Authentication is a robust tool for implementing user authentication. However, the official Firebase Admin SDK heavily depends on Node.js’s internal libraries, which aren’t available in Edge runtime environments like Cloudflare Workers or Vercel Edge Functions. This necessitates alternative solutions for using Firebase Authentication in such environments.

Edge-Compatible Authentication Library: next-firebase-auth-edge

To address this challenge, next-firebase-auth-edge has been developed. This library leverages the Web Crypto API to handle the creation and verification of custom ID tokens, enabling Firebase Authentication in Edge runtimes.

https://github.com/awinogrodzki/next-firebase-auth-edge

Features:

  • Compatibility with Latest Next.js Features: Supports functionalities like App Router and Server Components.
  • Zero Bundle Size: Avoids adding extra JavaScript code to the client bundle by handling all processes server-side.
  • Minimal Configuration: Eliminates the need for custom API routes or modifications to next.config.js; everything is managed through middleware.
  • Security: Utilizes the jose library for JWT verification, with user cookies signed using rotating keys to prevent cryptographic attacks.

For detailed setup instructions and usage examples, refer to the official documentation.

Utilizing Firestore in Edge Runtime Environments

While solutions like next-firebase-auth-edge exist for Firebase Authentication, there was a lack of suitable libraries for Firestore in Edge environments. To bridge this gap, I developed firebase-rest-firestore. This REST API client facilitates Firestore operations in Edge runtimes and offers the following features:

https://github.com/nabettu/firebase-rest-firestore

  • Edge Runtime Compatibility: Operates in environments where the Firebase Admin SDK is unavailable.
  • Comprehensive CRUD Support: Supports creation, reading, updating, and deletion of documents.
  • TypeScript Support: Provides type definitions for seamless development.
  • Token Caching for Performance: Implements token caching to enhance performance.
  • Intuitive API: Offers a straightforward interface, mirroring the Firebase Admin SDK’s design.

Usage Example:

import { createFirestoreClient } from "firebase-rest-firestore";

// Create a client with your configuration
const firestore = createFirestoreClient({
  projectId: "your-project-id",
  privateKey: "your-private-key",
  clientEmail: "your-client-email",
});

// Create a document with an auto-generated ID
const gameRef = firestore.collection("games").doc();
await gameRef.set({
  name: "The Legend of Zelda",
  genre: "Action-adventure",
  releaseYear: 1986,
});

// Read the document
const doc = await gameRef.get();
console.log(doc.data());

// Update the document
await gameRef.update({
  releaseYear: 1987,
});
Enter fullscreen mode Exit fullscreen mode

For more information, visit the firebase-rest-firestore GitHub repository.

Conclusion

Overcoming the limitations of Firebase services in Edge runtime environments is crucial for cost-effective and efficient application development. By leveraging libraries like next-firebase-auth-edge and firebase-rest-firestore, developers can implement authentication and database operations in Edge environments, optimizing both performance and costs.

If you found this information helpful, consider starring the firebase-rest-firestore GitHub repository.

https://github.com/nabettu/firebase-rest-firestore

Heroku

Deploy with ease. Manage efficiently. Scale faster.

Leave the infrastructure headaches to us, while you focus on pushing boundaries, realizing your vision, and making a lasting impression on your users.

Get Started

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

If you found this post useful, please drop a ❤️ or leave a kind comment!

Okay