Handle images received from my backend
Answered
Silver Fox posted this in #help-forum
Silver FoxOP
Basically my users have a profileImg and I've been storing it to the database with a POST operation on the backend. Now I want to recieve it on the frontend.
It actually works to receive the img on Postman.
On the frontend I'm running:
and this how the blob looks like:
blob:nodedata:41bf247f-a4da-4e41-ac8d-ffe40a5ab3cc
I've added this on my config file:
/ @type {import('next').NextConfig} */
const NextConfig = {
images: {
unoptimized: true,
remotePatterns: [
{
protocol: 'http',
hostname: '',
}
]
},
}
module. exports = NextConfig;
It actually works to receive the img on Postman.
On the frontend I'm running:
and this how the blob looks like:
blob:nodedata:41bf247f-a4da-4e41-ac8d-ffe40a5ab3cc
I've added this on my config file:
/ @type {import('next').NextConfig} */
const NextConfig = {
images: {
unoptimized: true,
remotePatterns: [
{
protocol: 'http',
hostname: '',
}
]
},
}
module. exports = NextConfig;
Answered by joulev
yes so you are running
code written directly in discord, not tested. let me know if it throws some errors or doesn't work
getUserImage on the server, which causes the bug. getUserImage should be run on the browser."use client";
// import statements...
function UserImage({ id }: { id: string }) {
const [url, setUrl] = useState<string | null>(null);
useEffect(() => {
(async () => {
const image = await getUserImage(id);
setUrl(image);
})();
return () => {
if (url) URL.revokeObjectURL(url);
};
}, [id]);
if (!url) return <PlaceholderImage />;
// next/image doesn't offer any benefits in this case
return <img src={url} ... />;
}code written directly in discord, not tested. let me know if it throws some errors or doesn't work
33 Replies
user uploads image in frontend, you send it to backend, and you want to show it to user?
@Anay-208 so If i'm right
Silver FoxOP
That what I want to achieve yes.
Also other people see it ofcourse but still same same, I think its a frontend issue since its working on postman both of the request (recieve and post)
Also other people see it ofcourse but still same same, I think its a frontend issue since its working on postman both of the request (recieve and post)
Silver FoxOP
barely know what that is, new to next.js
@Silver Fox barely know what that is, new to next.js
how are you suppose to deliver images if you aren't using a cdn for it
For image files, its best to use a cdn for images like aws s3 or cf r2
Silver FoxOP
Im using blobs
it doesn't work you mean?
@Silver Fox Im using blobs
It does work for storing actually
blob is not a good option imo
storing in database will lead to increase in latency
if you want to continue, you'll have to store blob in db, and send it to the frontend when requested.
Silver FoxOP
Id like to try it yeah
Before I used Google Clouds to recieve and send images
But I want to keep it simple for now
I've tried that only. It takes >5 seconds for images to be transferred to frontend then
Silver FoxOP
with blob?
yup
Silver FoxOP
Ok so you would recommend to use Clouds instead?
yes, I personally use cloudflare r2 because it has a very generous free tier and transparent pricing
aws s3 can also be used
So in Summary, its not a good idea to use blob.
Its better to use a cloud provider like aws s3 or cloudflare r2
Its better to use a cloud provider like aws s3 or cloudflare r2
@Anay-208 So in Summary, its not a good idea to use blob.
Its better to use a cloud provider like aws s3 or cloudflare r2
@Silver Fox Can you mark this message as a solution, by right clicking apps mark solution
blob:nodedata then you are running it on nodejs which wont work
you need to create the blob in the browser
show some code
Silver FoxOP
## Component:
import { getUserImage } from "./services/services";
import Image from "next/image";
export default async function Home() {
const userImage = await getUserImage("237ae2c7-8e56-4383-83ac-d8ac52c5be5e")
return (
<main>
<Image
src={userImage}
alt="User Profile Image"
width={500}
height={500}
/>
</main>
)
}
## Fetch Function:
export const getUserImage = async (id: string): Promise<string> => {
try {
const response = await fetch(
if (!response.ok) {
throw new Error(
}
const data = await response.blob();
const img = URL.createObjectURL(data);
return img;
} catch (error:any) {
console.error('Error fetching user image:', error.message);
throw error; // Re-throw the error to handle it in the calling code
}
};
## Backend functionality:
export async function getSpecificUserProfileImg(req, res) {
const id = req.params.userId;
const user = await User.findByPk(id);
if (!user) {
res.status(404);
}
res.setHeader('Content-Type', 'image/jpeg');
res.status(200).send(user.ProfileImg);
}
import { getUserImage } from "./services/services";
import Image from "next/image";
export default async function Home() {
const userImage = await getUserImage("237ae2c7-8e56-4383-83ac-d8ac52c5be5e")
return (
<main>
<Image
src={userImage}
alt="User Profile Image"
width={500}
height={500}
/>
</main>
)
}
## Fetch Function:
export const getUserImage = async (id: string): Promise<string> => {
try {
const response = await fetch(
${BACKEND_URL}/user/${id}/profileImg);if (!response.ok) {
throw new Error(
HTTP error! Status: ${response.status});}
const data = await response.blob();
const img = URL.createObjectURL(data);
return img;
} catch (error:any) {
console.error('Error fetching user image:', error.message);
throw error; // Re-throw the error to handle it in the calling code
}
};
## Backend functionality:
export async function getSpecificUserProfileImg(req, res) {
const id = req.params.userId;
const user = await User.findByPk(id);
if (!user) {
res.status(404);
}
res.setHeader('Content-Type', 'image/jpeg');
res.status(200).send(user.ProfileImg);
}
@Silver Fox ## Component:
import { getUserImage } from "./services/services";
import Image from "next/image";
export default async function Home() {
const userImage = await getUserImage("237ae2c7-8e56-4383-83ac-d8ac52c5be5e")
return (
<main>
<Image
src={userImage}
alt="User Profile Image"
width={500}
height={500}
/>
</main>
)
}
## Fetch Function:
export const getUserImage = async (id: string): Promise<string> => {
try {
const response = await fetch(`${BACKEND_URL}/user/${id}/profileImg`);
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const data = await response.blob();
const img = URL.createObjectURL(data);
return img;
} catch (error:any) {
console.error('Error fetching user image:', error.message);
throw error; // Re-throw the error to handle it in the calling code
}
};
## Backend functionality:
export async function getSpecificUserProfileImg(req, res) {
const id = req.params.userId;
const user = await User.findByPk(id);
if (!user) {
res.status(404);
}
res.setHeader('Content-Type', 'image/jpeg');
res.status(200).send(user.ProfileImg);
}
yes so you are running
code written directly in discord, not tested. let me know if it throws some errors or doesn't work
getUserImage on the server, which causes the bug. getUserImage should be run on the browser."use client";
// import statements...
function UserImage({ id }: { id: string }) {
const [url, setUrl] = useState<string | null>(null);
useEffect(() => {
(async () => {
const image = await getUserImage(id);
setUrl(image);
})();
return () => {
if (url) URL.revokeObjectURL(url);
};
}, [id]);
if (!url) return <PlaceholderImage />;
// next/image doesn't offer any benefits in this case
return <img src={url} ... />;
}code written directly in discord, not tested. let me know if it throws some errors or doesn't work
Answer
@joulev yes so you are running `getUserImage` on the server, which causes the bug. `getUserImage` should be run on the browser.
tsx
"use client";
// import statements...
function UserImage({ id }: { id: string }) {
const [url, setUrl] = useState<string | null>(null);
useEffect(() => {
(async () => {
const image = await getUserImage(id);
setUrl(image);
})();
return () => {
if (url) URL.revokeObjectURL(url);
};
}, [id]);
if (!url) return <PlaceholderImage />;
// next/image doesn't offer any benefits in this case
return <img src={url} ... />;
}
code written directly in discord, not tested. let me know if it throws some errors or doesn't work
Silver FoxOP
I dont get it to work somehow unfortunately. Think I need a break
@Silver Fox I dont get it to work somehow unfortunately. Think I need a break
any error you got? you need to create a client component for this
Silver FoxOP
Worked now thanks everyone!