Image proxy
Answered
British Shorthair posted this in #help-forum
British ShorthairOP
I'm working on a project where I've set up an API route (api/proxy) with the intention of downloading images and serving them to the client-side. This is to facilitate the use of images from Instagram's CDN in my frontend application.
While I am able to receive the URL from my API, I'm encountering an issue where the image isn't rendering correctly when I use <img src={response} /> in my React component. The image doesn't appear as expected.
Could anyone offer some insights or advice on this matter? It's worth noting that when I implement similar logic in a standalone server setup, it works fine and the images are displayed correctly on the client-side.
Thank you in advance!
While I am able to receive the URL from my API, I'm encountering an issue where the image isn't rendering correctly when I use <img src={response} /> in my React component. The image doesn't appear as expected.
Could anyone offer some insights or advice on this matter? It's worth noting that when I implement similar logic in a standalone server setup, it works fine and the images are displayed correctly on the client-side.
Thank you in advance!
Answered by Ray
import { NextRequest, NextResponse } from "next/server";
export function GET(req: NextRequest) {
const searchParams = new URL(req.url).searchParams;
const imageUrl = searchParams.get("url");
if (typeof imageUrl !== "string" || !imageUrl.startsWith('http')) {
return new NextResponse("Url is required", { status: 400 });
}
try {
return fetch(imageUrl);
} catch (error) {
return new NextResponse("Error fetching image", { status: 500 });
}
}11 Replies
British ShorthairOP
Like this?
@British Shorthair Like this?
import { NextRequest, NextResponse } from "next/server";
export function GET(req: NextRequest) {
const searchParams = new URL(req.url).searchParams;
const imageUrl = searchParams.get("url");
if (typeof imageUrl !== "string" || !imageUrl.startsWith('http')) {
return new NextResponse("Url is required", { status: 400 });
}
try {
return fetch(imageUrl);
} catch (error) {
return new NextResponse("Error fetching image", { status: 500 });
}
}Answer
British ShorthairOP
Yo Ray, you the best. No its working.
The reason that I have to return the fetch is because the logic to create the image is already being handles in the client?
The reason that I have to return the fetch is because the logic to create the image is already being handles in the client?
yes
does it work?
British ShorthairOP
Yes it works, thanks a lot
cool, please mark solution
keep in mind that the second argument for route handler in app router is not res
British ShorthairOP
Thanks
np