From f6a3b9eb6061219dfd032c9b55071c769591221f Mon Sep 17 00:00:00 2001 From: Paris Smirlakis Date: Mon, 23 Sep 2024 19:31:36 +0300 Subject: [PATCH] added middleware to handle validations --- src/middleware.ts | 39 +++++++++++++++++++++++++++++++++++++++ src/pages/_app.tsx | 14 -------------- 2 files changed, 39 insertions(+), 14 deletions(-) create mode 100644 src/middleware.ts diff --git a/src/middleware.ts b/src/middleware.ts new file mode 100644 index 0000000..7121df1 --- /dev/null +++ b/src/middleware.ts @@ -0,0 +1,39 @@ +import { NextResponse } from 'next/server'; +import type { NextRequest } from 'next/server'; +import { validateEnv } from "@/env.mjs"; + +export function middleware(request: NextRequest) { + try { + // Validate client-side environment variables + validateEnv(); + } catch (error: any) { + console.error(error.message); + + // Optionally, you can customize the response or redirect to an error page + return new NextResponse( + JSON.stringify({ + error: 'Internal Server Error', + message: error.message, + }), + { + status: 500, + headers: { 'Content-Type': 'application/json' }, + } + ); + } + + // Proceed with the request if validation passes + return NextResponse.next(); +} + +// Configure the middleware to match all routes except for static files and API routes +export const config = { + matcher: [ + /* + * Match all request paths except for the ones starting with: + * - /_next/image (image optimization files) + * - /favicon.ico (favicon file) + */ + '/((?!api|_next/static|_next/image|favicon.ico).*)', + ], +}; diff --git a/src/pages/_app.tsx b/src/pages/_app.tsx index bd2a050..6faf3d7 100644 --- a/src/pages/_app.tsx +++ b/src/pages/_app.tsx @@ -105,17 +105,3 @@ export default function App(props: AppProps) { ); } - -App.getInitialProps = async (appContext: AppContext) => { - // Only validate on the server side - if (typeof window === 'undefined') { - validateEnv(); - } - - // Call the default implementation of getInitialProps - const appProps = await import('next/app').then(({ default: NextApp }) => - NextApp.getInitialProps(appContext) - ); - - return { ...appProps }; -}; \ No newline at end of file