Skip to content

Commit

Permalink
added middleware to handle validations
Browse files Browse the repository at this point in the history
  • Loading branch information
smirlakis committed Sep 23, 2024
1 parent ac8188f commit f6a3b9e
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 14 deletions.
39 changes: 39 additions & 0 deletions src/middleware.ts
Original file line number Diff line number Diff line change
@@ -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).*)',
],
};
14 changes: 0 additions & 14 deletions src/pages/_app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -105,17 +105,3 @@ export default function App(props: AppProps) {
</AppCacheProvider>
);
}

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 };
};

0 comments on commit f6a3b9e

Please sign in to comment.