How can I use middleware in my Next.js application to catch and manipulate responses received from an external API?
The function below is executed from a Server Component.
export async function fetchData() {
const response = await fetch('https://localhost:3000/api/endpoint');
if(!response.ok) { throw new Error('Failed to fetch data') }
return response
}
Here is my endpoint located inside the file /app/api/endpoint/route.tsx
:
import { NextResponse } from "next/server";
export async function GET() {
const apiResponse = await fetch('https://my-external-api.com/endpoint');
//Do something that's useful in the middleware
const data = await apiResponse.json()
return NextResponse.json(data)
}
Here is my /src/middleware.tsx
import { NextRequest, NextResponse } from "next/server";
const middleware = async (request: NextRequest) => {
console.log(request)
console.log(NextResponse)
}
export default middleware;
I need to make some changes to the response sent back to the fetchData()
function. I could do it in the route handler itself, but that would mean a lot of code repetition.