Show a variety of randomly selected pictures from various sources using the command image/next

I'm in the process of building a basic news aggregation website using Next.js. I’ve run into an issue where I need to include specific domains in my next.config file for the Image component to work properly. The problem is, the URLs for the images on these domains are completely random. Is there a way to still use the Image component or should I just stick with the plain old image tag?

Answer №1

If you want to display images, one option is to upload them to a cloud storage before showing them, or you can use an internal Next API route to proxy image requests. Here's an example of how you can achieve this:

// pages/api/image_proxy.ts
// Remove type definitions if not using TypeScript
export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  const { source } = req.query;

  if (!source || typeof source !== "string") {
    return res
      .status(400)
      .json({ message: "Image source missing in request-query" });
  }
  const rStream = (await fetch(decodeURIComponent(source)).then(
    (resp) => resp.body
  )) as NodeJS.ReadableStream;

  if (!rStream) {
    // Failed to fetch
    // Options include redirecting to source URL or displaying error message
    return res.status(500).json({ message: "Internal server error" });
  }

  const pt = new Stream.PassThrough();

  stream.pipeline(rStream, pt, (err) => {
    if (err) return res.status(500).json({ message: "Internal server error" });
  });

  pt.pipe(res);
}

Simply route all URL sources through the specified route like this:

<Image
      src={`/api/image_proxy?source=${encodeURIComponent(YOUR_IMAGE_SRC_URL)}`}
   />

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Distinguishing Between Angular and Ajax When Making Requests to a NodeJS Server

Trying to establish communication between an Angular client and a NodeJS server. Previous method using JQuery $.ajax({ url: "/list", type: "POST", contentType: "application/json", dataType: "json", success: function(data) { console.log("Data ...

When either the post request body or header is set, Next-auth's getSession function will return null

I've been working on implementing a post request in nextjs using the next-auth package. I noticed that when making a get request without setting headers or body, the await getSession({ req }); function on the server returns the correct data. However, ...

Creating custom shaders for YouTube videos within a Three.js userscript

I want to add a shader effect to YouTube videos. My current approach involves using Three.js to implement a shader on a video. Specifically, I am trying to adapt this example of applying a shader to a video (code available here) into a Tampermonkey usersc ...

Creating an Interactive and Engaging 3D Experience on Facebook with the Power of Javascript API

Looking for suggestions on a 3D API in JavaScript that can be used to create immersive applications on Facebook. Is there something similar to this one: ? Appreciate any insights. ...

A different approach to joining strings

Is there a different method to combine a '#' symbol like in the code snippet below? radioButtonID = '#' + radioButtonID; ...

Guide on leveraging a private GitHub repository as a yarn dependency without installing internal dependencies

Recently, I have been attempting to incorporate a private GitHub repository as a dependency within multiple repositories at my workplace. Within the primary package.json file, our dependency is outlined as follows: "mycompany-models": "https://github.com ...

The mouse movement event will not be triggered for every frame when a keyboard event occurs

When the mouse is moving in a browser, ideally the mousemove event should fire every frame. However, if a key is pressed or released (or repeated), the mousemove event stops firing for a frame or two. To test this behavior, you can use the code snippet bel ...

CSS struggles after implementing conditional checks in return statement for an unordered list

I'm encountering a CSS issue with the header section. When I include the following code snippet in my code to display a tab based on a condition, the entire header list doesn't appear in a single horizontal line: <div> {isAdmin(user) ? ...

Implementing data updates in Vue.js within a Mongoose database, along with making API

I've encountered an issue where I need to update a count variable representing the votes each video receives after using GET and POST functions to retrieve and save URLs in my database. Additionally, I'm looking to disable the voting button once ...

The dataTable plugin is malfunctioning, displaying all records on a single page when it should only show 10 per page

I utilized the dataTable plugin to format my HTML table, but unfortunately it is not displaying the results as expected. Instead of showing 10 records per page, it is displaying all records at once. I even tried setting "iDisplayLength: 10" but it didn&apo ...

Tips for styling the json response received from a servlet with jquery ajax

I am attempting to display a list of users returned from a servlet using jQuery ajax. The first script block is functioning well, successfully presenting the list of users in a formatted manner but experiencing issues passing form parameters such as text a ...

Navigating through a Single Page Application (SPA) can be achieved without

Can the CSS (Level 4) @document rule handle URLs that have the # symbol or include query parameters? For those who are not familiar with this topic Currently, only Firefox supports this feature with the @-moz-document prefix. If other browsers start supp ...

Angular-material's Md-dialog popup box is displayed as a separate view within the Yeoman framework

I have recently created a project using Yeoman (angular-fullstack, angular-material) and encountered an issue with triggering the md-dialog box. When clicking on a div element, the dialog box is supposed to appear. However, instead of showing the popup the ...

Troubleshooting Vercel's caching of CORS headers across different domains

I currently have a Next.js API hosted on Vercel that is being utilized by various domains. One issue I'm facing is when the browser sends the If-None-Match header, Vercel replies with a 304 status; however, the Access-Control-Allow-Origin header may ...

Managing the automatic download of a zip file through JQuery - A guide

When working with a REST API and creating a zip file for forced download, the task is to call the API by sending necessary POST data through JQuery to initiate the download. How can this goal be accomplished effectively? ...

Exploring the process of implementing functions on buttons in Three.js

I have a written program in Three JS that I want to enhance by adding an animated function triggered by a button click event. Additionally, I need help with setting buttons in an inner window and calling all animations on button click events. Any assistanc ...

Dealing with browser timeouts for HTTP requests using JavaScript

Managing time out situations in a web application when calling a REST API is crucial. Below is the code snippet I am using to make the API call with jQuery ajax. $.ajax({ type: "POST", url: endpoint, data: payload, ...

Utilizing Next.js to dynamically update data within a div element upon

I have a table set up to display data and I want to transfer the row data into a div when the user clicks on a table row: Currently, I can successfully get the data onclick: const handleClick = (rowData) => { console.log(rowData); } However, I am ...

Issue with jQuery DataTable: Unable to use column-level filters at the top and maintain a fixed height simultaneously

I am having an issue displaying data in a jQuery DataTable with a column level filter at the top, fixed height, and scroller enabled. Initially, I was able to display the column level filter at the top and it was functioning properly. However, when I set t ...

Which is the better option: utilizing the submit event of the form, or incorporating ajax functionality?

Forms are an essential part of my website design, and I often find myself contemplating whether it's better to submit a form using a standard submit button or utilizing Ajax. Typically, I opt for Ajax to prevent the dreaded issue of form re-submission ...