Router

Harpia provides a high-performance and clean API for defining routes, handling dynamic parameters, and organizing your application into modules or groups.

Basic Routing

The Application class (via harpia()) exposes shorthand methods for all common HTTP verbs.

import harpia from "@harpiats/core";

const app = harpia();

app.get("/", (req, res) => {
  res.send("Welcome home!");
});

app.post("/users", (req, res) => {
  res.status(201).json({ message: "User created" });
});

Supported Methods

  • app.get(path, ...handlers)
  • app.post(path, ...handlers)
  • app.put(path, ...handlers)
  • app.patch(path, ...handlers)
  • app.delete(path, ...handlers)
  • app.head(path, ...handlers)
  • app.options(path, ...handlers)

Route Parameters

You can define dynamic segments in your paths using the colon : prefix. These parameters are automatically extracted and available in req.params.

app.get("/users/:id", (req, res) => {
  const userId = req.params.id;
  res.send(`User ID is: ${userId}`);
});

Nested Parameters

You can also use multiple parameters in a single path:

app.get("/posts/:postId/comments/:commentId", (req, res) => {
  const { postId, commentId } = req.params;
  res.json({ postId, commentId });
});

Route Middleware

Harpia allows you to pass multiple handlers to a route. All handlers except the last one act as route-specific middleware.

const auth = (req, res, next) => {
  if (req.headers.get("Authorization")) {
    return next();
  }
  res.status(401).send("Unauthorized");
};

app.get("/dashboard", auth, (req, res) => {
  res.send("Welcome to your dashboard");
});

Organizing Routes

For larger applications, you can use the Router class to group routes and then register them into the main application.

// routes/users.ts
import { Router } from "@harpiats/core";

const userRouter = new Router("/users");

userRouter.get("/", (req, res) => {
  res.send("User list");
});

userRouter.get("/:id", (req, res) => {
  res.send(`User ${req.params.id}`);
});

export { userRouter };

Registering Routers

Use the app.routes() method to register an external router.

import { userRouter } from "./routes/users";

app.routes(userRouter);

Prefixes

When you create a new Router("/prefix"), all routes defined within that router will automatically be prefixed with /prefix.

WebSocket Routes

Harpia also supports WebSocket routing directly through the router.

app.ws("/chat", {
  open(ws) {
    console.log("Connection opened");
  },
  message(ws, message) {
    ws.send(`Echo: ${message}`);
  },
});

For more details on real-time communication, see the WebSocket documentation.