Skip to content

Commit 9896c5f

Browse files
Simplify middleware (#33)
1 parent cae92a5 commit 9896c5f

2 files changed

Lines changed: 15 additions & 14 deletions

File tree

README.md

Lines changed: 3 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -93,7 +93,7 @@ $ bun add --dev tidewave
9393

9494
Then, configure it:
9595

96-
Create `pages/api/tidewave/[...all].ts` with:
96+
Create `pages/api/tidewave.ts` with:
9797

9898
```typescript
9999
import type { NextApiRequest, NextApiResponse } from 'next';
@@ -128,14 +128,8 @@ Then create (or modify) `middleware.ts` with:
128128
import { NextRequest, NextResponse } from 'next/server';
129129

130130
export function middleware(req: NextRequest): NextResponse {
131-
const { pathname } = req.nextUrl;
132-
133-
if (pathname === '/tidewave') {
134-
return NextResponse.rewrite(new URL(`/api/tidewave/index`, req.url));
135-
}
136-
137-
if (pathname.startsWith('/tidewave')) {
138-
return NextResponse.rewrite(new URL(`/api${pathname}`, req.url));
131+
if (req.nextUrl.pathname.startsWith('/tidewave')) {
132+
return NextResponse.rewrite(new URL(`/api/tidewave`, req.url));
139133
}
140134

141135
// Here you could add your own logic or different middlewares.

src/next-js.ts

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,18 @@ export async function tidewaveHandler(
5353
return async function handler(req: NextApiRequest, res: NextApiResponse): Promise<void> {
5454
const origin = req.headers.host;
5555

56+
// Parse endpoint manually, rewrite doesn't populate query
57+
const url = new URL(req.url ?? '', `http://${origin}`);
58+
const segments = url.pathname.split('/').filter(Boolean);
59+
const [_tidewave, endpoint] = segments;
60+
61+
// Note that this is the original request URL, not accounting for
62+
// Next.js rewrite. We validate that the request targets /tidewave,
63+
// rather than /api/tidewave.
64+
if (!url.pathname.startsWith('/tidewave')) {
65+
return res.status(404).json({ message: 'This route only works when accessed at /tidewave' });
66+
}
67+
5668
if (origin) {
5769
const [hostname, port] = origin.split(':');
5870
config.host = hostname ? hostname : config.host;
@@ -64,11 +76,6 @@ export async function tidewaveHandler(
6476
await connectWrapper(securityMiddleware)(req, res, next);
6577
await connectWrapper(bodyParser.json())(req, res, next);
6678

67-
// Parse endpoint manually, rewrite doesn't populate query
68-
const url = new URL(req.url ?? '', `http://${origin}`);
69-
const segments = url.pathname.split('/').filter(Boolean);
70-
const [_tidewave, endpoint] = segments;
71-
7279
if (req.method === 'GET' && endpoint === undefined) {
7380
return await respondTidewaveHTML(res, config);
7481
}

0 commit comments

Comments
 (0)