You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
This API is built using [Hono](https://hono.dev/) and serves as a starter kit for building scalable and secure backend applications. It includes authentication, protected routes, rate limiting, and structured routing.
4
+
Our API is built using **Hono**, a fast and lightweight web framework designed to handle API requests efficiently. The API adheres to **RESTful principles**, ensuring a consistent and intuitive interface for users. It integrates **Redis** for rate limiting and caching, enhancing performance and preventing abuse. The architecture is structured to be easily extendable and secure.
6
5
7
6
## Features
8
-
-**Authentication** with middleware
9
-
-**Protected routes** for secure endpoints
10
-
-**Rate limiting** using Redis
11
-
-**RESTful API structure**
12
-
-**Support for API clients** (Postman, Fetch API, cURL)
7
+
8
+
### 1. **Hono Framework**
9
+
-**Lightweight and Fast**: Hono is optimized for speed and minimal overhead, making it ideal for serverless environments like Cloudflare Workers.
10
+
-**Web Standards Compliance**: Built on web standards, Hono ensures compatibility across different platforms.
11
+
12
+
### 2. **Protected Routes**
13
+
-**Security via Middlewares**: The API uses middlewares to protect routes from unauthorized access. This includes authentication and authorization checks to ensure only authorized users can access sensitive data.
14
+
15
+
### 3. **Redis-based Rate Limiting**
16
+
-**Preventing Abuse**: Redis is used to implement rate limiting, preventing excessive requests from a single source and protecting against potential attacks.
17
+
18
+
### 4. **Authentication Middleware**
19
+
-**Protecting Routes**: Authentication middleware ensures that only authenticated users can access protected routes.
20
+
21
+
### 5. **Integration with TanStack Query**
22
+
-**Efficient Data Fetching and Mutations**: TanStack Query is used to optimize data fetching and mutations, reducing unnecessary requests and improving overall performance.
13
23
14
24
## Base URL
15
-
The API base URL depends on your environment:
16
25
17
-
-**Development:**`http://localhost:3000/api`
18
-
-**Production:**`<your-deployed-url>/api`
26
+
The base URL of the API varies depending on the environment:
The API exposes various endpoints for interacting with the backend.
5
+
This guide will walk you through adding a new API endpoint using the Hono framework for your server-side application. Follow the steps below to create new routes and handle API requests efficiently.
6
6
7
-
## 1. **Public Endpoints**
8
-
### `GET /api/hello`
9
-
Returns a simple greeting message.
7
+
### Steps to Add a New Endpoint
8
+
9
+
#### 1. **Navigate to the `routes/api.ts` File**
10
+
11
+
The primary location for defining your API routes is in the `server/routes/api.ts` file. This is where all core API endpoints should be defined.
12
+
13
+
#### 2. **Define the New Route**
14
+
15
+
Use Hono’s routing methods (`app.get`, `app.post`, `app.put`, etc.) to define a new route. Each route corresponds to an HTTP method and a URL pattern.
16
+
17
+
#### 3. **Implement Logic in the Handler Function**
18
+
19
+
In the handler function, implement the necessary logic to process the request. You can access request data, query parameters, headers, and more.
20
+
21
+
#### 4. **Return a JSON Response**
22
+
23
+
Ensure that your endpoint responds with a JSON object, especially for API responses. Hono's context (`c`) makes it easy to return structured JSON responses.
24
+
25
+
## Creating a New Router File
26
+
27
+
If your application grows and you need to organize your routes better, you can create a new file for each module (e.g., routes/users.ts). This can help maintain a clean structure as the project expands.
28
+
29
+
### Steps to create a new router file
30
+
31
+
#### 1. **Create a new file**
32
+
33
+
In the server/routes/ directory. For example, you can create server/routes/users.ts for user-related routes.
34
+
35
+
#### 2. **Define your routes**
36
+
37
+
using Hono’s routing methods (app.get, app.post, etc.) in the new file.
38
+
39
+
#### 3. **Import and use the new router**
40
+
41
+
in the main server configuration file (e.g., server.ts).
42
+
43
+
44
+
### Example of creating a ` Users ` router
45
+
46
+
Create a file, `server/routes/users.ts`, where you define routes related to user management:
10
47
11
-
**Request:**
12
48
```ts
13
-
app.get('/hello', (c) => {
14
-
returnc.json({ message: 'Hello from Hono API!' });
49
+
import { Hono } from'hono';
50
+
51
+
const app =newHono();
52
+
53
+
app.get('/api/users', (c) => {
54
+
// Logic to retrieve all users
55
+
const users =getAllUsers(); // Assume this function fetches user data
56
+
returnc.json(users); // Return the response as JSON
15
57
});
58
+
59
+
exportdefaultapp;
60
+
```
61
+
62
+
Then, ensure that the `users.ts` router is imported and used in the main server setup `server.ts`
63
+
64
+
File: ` server.ts `
65
+
66
+
```ts
67
+
import { Hono } from'hono';
68
+
importusersfrom'./routes/users.ts'
69
+
70
+
const app =newHono();
71
+
72
+
app.router('/api/users', users);
73
+
74
+
exportdefaultapp;
75
+
```
76
+
77
+
You can also define a router file for defining all the routes and then importing the file in `server.ts`. For more best
78
+
practices regarding hono you can refer to their official docs [Hono Best Practices](https://hono.dev/docs/guides/best-practices).
Some API routes require user authentication to access.
3
+
Hono has built-in support for [middlewares](https://hono.dev/docs/guides/middleware), which are functions that can be used to modify the context or execute code before or after a route handler is executed.
4
4
5
-
## Middleware-Based Protection
5
+
That's how we can secure our API endpoints from unauthorized access. Below are some examples of you can leverage middlewares to protect your API routes.
6
6
7
-
We use the `authMiddleware` to enforce authentication for specific routes.
7
+
## Authenticated access
8
8
9
-
### **Middleware: `authMiddleware`**
9
+
After validating the user's authentication status using next-auth, it automatically stores the user data in sessions object. This allows us to access the user's information in subsequent middleware and procedures without having to re-validate the session.
10
+
11
+
We have already provided with a auth middleware which yo can find at `server/middlewares/auth-middleware.ts` which provides with basic authenticated access.
returnc.json({ message: "Protected API Data", name: user.name });
21
45
});
46
+
```
47
+
48
+
## Feature-based access
49
+
50
+
To implement feature-based access, such as role-based access control (RBAC), you can define a middleware that checks the user's role before allowing access to certain routes.
51
+
52
+
Here's an example of how you can create a role-based access middleware:
This app supports various HTTP methods, and all requests are handled in `src/app/api/[...routes]/route.tsx`.
3
+
This app supports various HTTP methods, and all requests are handled in `src/app/api/[...routes]/route.tsx`. It exports all the related HTTP methods so you only need to make the api call using your preferred method and you are good to go.
Each exported method is responsible for handling the corresponding HTTP request and routing it to the appropriate logic within the app.
16
+
15
17
## Example GET Request using TanStack Query
16
18
17
-
To call a GET request using TanStack Query, you can use the `useQuery` hook as shown below:
19
+
TanStack Query is a powerful library for managing server state in React applications. You can use it to call API endpoints like the one you’ve defined in your route.tsx file.
20
+
21
+
Using TanStack Query in combination with your Hono API client allows you to manage server-state in a declarative way while handling various HTTP methods such as GET, POST, PUT, DELETE, and PATCH. By leveraging TanStack Query, It can simplify state management, automatically handle caching and refetching.
22
+
23
+
Here’s how you can perform a GET request to fetch data using TanStack Query:
18
24
19
25
```ts
20
26
import { useQuery } from'@tanstack/react-query';
21
27
22
28
const fetchHello =async () => {
23
-
const res =awaitfetch("/api/hello");
24
-
if (!res.ok) thrownewError("Failed to fetch data");
## Handling POST, PUT, DELETE Requests with TanStack Query
56
+
57
+
Just like with GET requests, you can also use TanStack Query for making POST, PUT, DELETE, or PATCH requests to your API. Below are some examples of how to handle these HTTP methods.
58
+
59
+
### Example: Making a POST Request
60
+
61
+
For sending data (e.g., creating a new resource), use the `mutate` function from the `useMutation` hook:
0 commit comments