From 5d3b9b2b2cb0e3a81ac60fca72a6125bff92c07a Mon Sep 17 00:00:00 2001 From: ghosind Date: Tue, 26 Nov 2024 23:11:37 +0800 Subject: [PATCH 1/2] feat: print error message on api proxy middleware Signed-off-by: ghosind --- src/middleware.ts | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/src/middleware.ts b/src/middleware.ts index 1af3d0a..98eb6d5 100644 --- a/src/middleware.ts +++ b/src/middleware.ts @@ -1,3 +1,4 @@ +import { AxiosError } from 'axios'; import { cookies } from 'next/headers'; import { NextResponse } from 'next/server'; @@ -44,7 +45,13 @@ async function handleApiProxy(req: NextRequest) { status: resp.status, headers: resp.headers, }); - } catch (error: any) { + } catch (error: AxiosError | any) { + if (error instanceof AxiosError) { + console.error(error?.cause || error?.message || error); + } else { + console.error(error); + } + return NextResponse.json({ message: error?.message || error || 'Something went wrong', }, { From 0219a46dfda6f7b1b0c39bda6e7f6de778e9cd84 Mon Sep 17 00:00:00 2001 From: ghosind Date: Tue, 10 Dec 2024 23:25:53 +0800 Subject: [PATCH 2/2] feat: throw error if no API_SERVER set Signed-off-by: ghosind --- src/middleware.ts | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/src/middleware.ts b/src/middleware.ts index 98eb6d5..a0dc8b0 100644 --- a/src/middleware.ts +++ b/src/middleware.ts @@ -27,12 +27,18 @@ const protectedPaths = new Set([ async function handleApiProxy(req: NextRequest) { try { + const baseUrl = process.env.API_SERVER; + if (!baseUrl) { + throw new Error('The API server is not configured, please check API_SERVER environment variable'); + } + + const path = req.nextUrl.pathname.replace('/api/', '/') + const url = new URL(path, baseUrl); + const headers: Record = {}; req.headers.forEach((value, key) => { headers[key] = value }); - const path = req.nextUrl.pathname.replace('/api/', '/') - const url = new URL(path, process.env.API_SERVER); const resp = await fetch(url, { method: req.method,