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

Send a JSON string directly to Google Cloud Storage without the need for a file upload

When I need to receive data in the form of a JSON string from an external source and then upload it directly to Google Cloud Storage without saving it as a local file first, is there a way to accomplish this task? Thank you. storage .bucket(bucketName) ...

Issue with VueJS 2 and TypeScript: computed value unable to recognize property specified in data object

When creating the following component: <template lang="html"> <div> <p>{{ bar }}</p> </div> </template> <script lang="ts"> import Vue from 'vue'; export const FooBar = Vue.ex ...

Is it possible to utilize Apollo GraphQL with Next.js without the need for installing react-router-dom?

When using ApolloProvider, an app is wrapped with the following code: <ApolloProvider client={client}> <App /> </ApolloProvider> An issue arises in Nextjs where route components can be declared in the pages folder without adding them ...

Negative vibes with for/in loop

My script is short and simple: hideElements = arguments.shift().split(','); for (iterator in hideElements) { console.log('--> hiding ' + hideElements[iterator]); lg_transitions({kind:"slide-up"}, {target: hideElements[iterat ...

Guide to selecting a specific year on a calendar using Selenium with JavaScript

While attempting to create a Selenium test using JavaScript, I encountered an issue with filling in calendar data through a dropdown menu: const {Builder, By, Key} = require('selenium-webdriver') const test2 = async () => { let driver = awa ...

Tips on altering a predetermined input text value using JavaScript

I have a question about using JavaScript. I am currently developing a tax calculation system. function calculateTax(){ var invoiceValue = document.getElementById("invoicevalue"); var ppn = document.getElementById("ppn"); var pph = document.get ...

What is the best way to display the complete text or wrap a menu item in an Angular Material menu?

Is it possible to display the full text of a menu item instead of automatically converting it to ellipses or breaking the word? I've tried various CSS methods without success. Any suggestions? https://i.stack.imgur.com/3l7gE.png #html code <mat-m ...

Execute the getJSON calls in a loop for a count exceeding 100, and trigger another function once all

In order to process a large grid of data, I need to read it and then make a call to a $getJSON URL. This grid can contain over 100 lines of data. The $getJSON function returns a list of values separated by commas, which I add to an array. After the loop fi ...

Get the data from the files in the request using request.files in Node.js

Is there a way to read the content of a file (either a txt or CSV file) that a user uploads without saving it to local storage? I know I can save the file in an upload directory and then read it from storage. However, I'm wondering if there is a way ...

Troubleshooting the malfunction of jQuery's change() function

There are three HTML select tags on my page. I want these three select tags to function as follows: When I change selectA, selectB should automatically update based on the selection in selectA. Similarly, when an option in selectB is created, changing se ...

The WebView.HitTestResult method is currently only receiving <img src> elements and not <a href> elements

I am attempting to open a new window in the Android browser using "_blank". I have set up an event listener for this purpose. mWebView.getSettings().setSupportMultipleWindows(true); mWebView.setWebChromeClient(new WebChromeClient() { ...

Troubleshooting problem with Angular's ng-repeat directive in dealing with varying number of child objects

I am currently dealing with tree-structured data where the parent nodes can have an indefinite number of children, and those children can also have an indefinite number of children, creating a deeply nested structure. While I have successfully formatted th ...

invisible recaptcha with synchronous ajax

Hey, I'm trying to figure out a solution on how to obtain the token or a valid response from Recaptcha and then proceed with running the ajax call. Does anyone have any suggestions on how to achieve this in a synchronous manner? Here's the proce ...

Customize date filtering in KendoUI grid

I am trying to modify the date format in the filter of my kendo grid. For example, I would like to change 1/30/2015 to Jan 30, 2015 I have successfully changed the date format for Start Date field: "StartDate", title: " ...

Changing the color of a tooltip for a specific element using Bootstrap 4

Is there a way to customize the tooltip background-color for icons with the classes "alert-danger" to red and "alert-success" to green using the following CSS commands: .alert-danger + .tooltip > .tooltip-inner { background-color: red !important; } ...

Removing the switcher outline in Bootstrap Switch: a step-by-step guide

I have implemented the bootstrap-switch - v3.3.1, however, I want to remove the default blue outline that appears around the switcher when toggling it on or off. Despite setting style="outline: 0 none; for the input, the outline remains visible. Below is ...

Persistent Angular Factory Variables Showing Outdated Data - Instances Stuck with Old Values

One of the challenges I faced was setting up a resource factory to build objects for accessing our API. The base part of the URL needed to be determined using an environment variable, which would include 'account/id' path segments when the admin ...

What could be the reason for TypeScript throwing an error that 'product' does not exist in type '{...}' even though 'product' is present?

Structure of Prisma Models: model Product { id String @id @default(auto()) @map("_id") @db.ObjectId name String description String price Float image String createdAt DateTime @default(now()) updatedAt Da ...

Troubleshooting a misformatted JSON string that lacks proper double quotes in Java Script

{ DataError: { user_id: [ [Object] ] } } I want to transform this string into JSON structure like below: { "DataError": { "user_id": [ [Object] ] } } Is there a potential method to achieve this outcome from incorrectly formatted JSON string? ...

How come the HTML page served by the express.js route isn't linked to a CSS stylesheet?

Recently, I've been working with a server.js file that imports a router const path = require("path"); const express = require("express"); const app = express(); const PORT = 8080; app.use(express.urlencoded({ extended: true })); app.use(express.jso ...