-
Clone the repo.
-
Run the following command inside the cloned repository to install all the dependencies :
npm install
-
Replace
wrangler.example.toml
withwrangler.toml
by removing the.example
from the name and replace the environment variables with actualprisma accelerate
anddatabase url
links, as they will be needed by the Cloudflare workers in production. For local development, use your localpostgres_db_link
and your personalprisma_accelerate_link
. -
Replace the
.env.example
file with.env
file and replace the enviornment variables there as well. -
If there's a problem in local development then : Create
.dev.vars
file in the root directory and copy the environment variables from.env
in that file. This will allow Hono to use the environment variables during local development. -
Run the following command to run the server locally :
npm run dev
- Hono.js and its application in creating a serverless service
- Serverless backends and Cloudflare workers themselves
- Prisma ORM and its accelerate features
This small project hs been created to be integrated with a Todo App(fr it's cringy I know!), this will be accessed by an express server and then that server would talk to the main React app. I never intended to finish it, but it was so on the verge man and another Todo App, ughh!
Edge Computing refers to the practice of processing data closer to where it is generated (i.e., at the "edge" of the network), rather than in a centralized data center. This reduces latency and bandwidth usage, leading to faster response times and more efficient processing.
- CDNs (Content Delivery Networks): Distribute content closer to the user to improve load times and reduce latency (e.g., Cloudflare, Akamai).
- Edge Functions: Small units of code that run at the edge of the network, near the user (e.g., Cloudflare Workers, Vercel Edge Functions).
- IoT (Internet of Things): Devices process data locally or at a nearby gateway rather than sending all data to a central server.
- Fog Computing: Extends cloud computing to the edge of the network, providing compute, storage, and networking services between end devices and cloud data centers.
- MEC (Multi-access Edge Computing): Provides IT service environment and cloud computing capabilities at the edge of the cellular network, closer to mobile users.
- Edge Caching: Stores frequently accessed data at the edge to improve access times and reduce load on the central server.
- Node.js Modules: Edge environments often don't support all Node.js modules, especially those related to file system operations, process management, or other server-specific functionalities.
- Resource Constraints: Edge environments have limits on memory, CPU, and execution time, which can affect packages that are resource-intensive.
- Compatibility: Some packages are designed with assumptions about the environment they will run in, which might not hold true in a constrained Edge environment.
-
Dependencies and Libraries: Edge environments, like those provided by Next.js's Edge Functions, often have limitations on the libraries and dependencies you can use. They are designed to be lightweight and may not support all Node.js modules.
-
Environment Constraints: Edge environments are typically more restrictive in terms of execution capabilities, available resources, and execution time. Libraries that rely on certain Node.js built-in modules or features may not work as expected.
-
Security Concerns: Edge environments are designed to run code closer to the user, which can introduce security concerns. JWT libraries often rely on cryptographic functions, and the availability or security of these functions might be restricted in an Edge environment.
jose
is a JavaScript library for JSON Web Tokens (JWTs) and related standards (JWS, JWE, etc.). It is often used in Edge environments because it is lightweight and designed to work without relying on Node.js-specific modules.
Example of using jose
in a Next.js Edge Function:
import { jwtVerify } from "jose";
export default async function handler(req) {
const token = req.headers.get("Authorization")?.split(" ")[1];
if (!token) {
return new Response("Unauthorized", { status: 401 });
}
try {
const { payload } = await jwtVerify(
token,
new TextEncoder().encode("your-SECRET-key")
);
return new Response(JSON.stringify(payload), { status: 200 });
} catch (error) {
return new Response("Unauthorized", { status: 401 });
}
}
export const config = {
runtime: "edge",
};
Hono.js is a lightweight, fast web framework for Cloudflare Workers. It simplifies the process of building serverless applications by providing a familiar routing and middleware structure.
Below is an example of how you might use Hono.js with Cloudflare Workers to create a simple API that includes JWT authentication and some basic routing.
-
Install Wrangler: The command-line tool to manage Cloudflare Workers.
npm install -g wrangler
-
Initialize a New Worker:
wrangler init my-worker cd my-worker
-
Install Hono.js:
npm install hono jose
-
Edit
wrangler.toml
: Make sure yourwrangler.toml
file is configured properly for your project. -
Edit
src/index.ts
(orsrc/index.js
if you're not using TypeScript):
import { Hono } from "hono";
import { jwt } from "hono/jwt";
import { jwtVerify } from "jose";
const app = new Hono();
// Middleware to verify JWT
const verifyJWT = async (ctx, next) => {
const token = ctx.req.headers.get("Authorization")?.split(" ")[1];
if (!token) {
return ctx.text("Unauthorized", 401);
}
try {
const { payload } = await jwtVerify(
token,
new TextEncoder().encode("your-SECRET-key")
);
ctx.set("user", payload);
await next();
} catch (error) {
return ctx.text("Unauthorized", 401);
}
};
// Public route
app.get("/", (ctx) => {
return ctx.text("Hello, World!");
});
// Protected route
app.get("/protected", verifyJWT, (ctx) => {
const user = ctx.get("user");
return ctx.json({ message: "This is a protected route", user });
});
// Start the Hono app
export default app;
- Build and Deploy:
wrangler publish
- Imports: Import necessary modules from Hono and jose.
- App Initialization: Initialize a new Hono application.
- JWT Middleware: Create a middleware function to verify JWT tokens. It extracts the token from the
Authorization
header, verifies it usingjose
, and attaches the payload to the context. - Routes:
- Public Route: A simple public route that returns "Hello, World!".
- Protected Route: A route protected by the JWT middleware. It returns a message and the user information extracted from the JWT.
- Deployment: Use Wrangler to build and deploy your worker to Cloudflare's edge network.
- Run JavaScript at the Edge: Execute code closer to the end user to reduce latency and improve performance.
- Serverless: No need to manage servers or infrastructure; Cloudflare handles scaling and availability.
- Flexible: Can handle various tasks such as serving static assets, modifying requests/responses, and running API endpoints.
- Performance: Reduced latency by running code closer to users.
- Scalability: Automatic scaling without the need for manual intervention.
- Cost Efficiency: Pay only for what you use, without the need for maintaining servers.
- Edge Computing reduces latency by processing data closer to the user.
- CDNs and Edge Functions are popular examples of edge computing.
- Some libraries, like those for JWTs, may not work in Edge environments due to dependencies on Node.js modules.
jose
is a lightweight JWT library compatible with Edge environments.- Edge environments have constraints that affect the compatibility of some Node.js packages.
Cloudflare Workers provide a serverless execution environment that allows you to run JavaScript code at the edge of the Cloudflare network. This means your code can run closer to your users, reducing latency and improving performance. Workers are often used for tasks like:
- Serving static content
- Manipulating HTTP requests and responses
- Implementing custom logic for routing and load balancing
- API gateways
- Authentication and authorization
- Handling serverless functions
- Dependencies and Libraries: Edge environments may not support all Node.js modules, leading to compatibility issues.
- Environment Constraints: Limited resources and execution capabilities can prevent some JWT libraries from working.
- Security Concerns: Cryptographic functions required by JWT libraries might be restricted in Edge environments.
- Edge Computing: Processing data closer to where it is generated, reducing latency and bandwidth usage.
- CDN (Content Delivery Network): Distributes content closer to the user to improve load times and reduce latency.
- CDNs: e.g., Cloudflare, Akamai.
- Edge Functions: e.g., Cloudflare Workers, Vercel Edge Functions.
- IoT (Internet of Things): Local processing on devices or nearby gateways.
- Fog Computing: Extends cloud services to the network edge.
- MEC (Multi-access Edge Computing): Provides cloud capabilities at the edge of cellular networks.
- Edge Caching: Stores frequently accessed data at the edge.
- Serverless Execution: Runs JavaScript at the edge, closer to users, improving performance and reducing latency.
- Use Cases: Serving static content, modifying HTTP requests/responses, API gateways, authentication, etc.
- Benefits: Scalability, cost efficiency, and reduced latency.
- Hono.js is a lightweight framework for Cloudflare Workers.