Is there a way for me to have Next.Js automatically download and serve all the external assets on my website?

Currently, I have been putting together a portfolio using headless WordPress and NextJs. To retrieve data from the GraphQl endpoint, I created my own functions which are working perfectly fine. However, my issue lies with media files such as images and pdfs that are stored on the WordPress CMS and brought into Next.Js as links (imported as external images) like this:

<img src="https://wordpresscms.mywebsite.com/uploads/2020/02/myimage.png" />

My goal is to have these assets hosted on the NextJs website and automatically updated during each build process. Is there a way to achieve this automatically within Next.Js? Or does this happen by default when the website is deployed to production?

The scenario I have envisioned goes as follows:

  1. I upload the assets to the WordPress cms.
  2. NextJs fetches the JSON data from WordPress containing links to external assets (using the GraphQL API at build time (getStaticProps)).
  3. NextJs downloads the assets.
  4. NextJs substitutes the external URLs with local URLs (hosted on the same host as my NextJs website).

Thank you.

Answer №1

There are two approaches that you might find intriguing:

  1. Closely resembling your initial concept

Following step 2, create a function to be utilized within getStaticProps. This function will iterate through the JSON containing links to external resources, retrieve each asset, and store them as files in an array or dictionary. Subsequently, pass this object to your page and distribute it across your application.

This method will fetch all assets during each build and display them wherever specified. However, it does not automatically update external URLs as desired - you must manually pass the files from getStaticProps to each element requiring this support.

You can reference the following resource to kickstart this process: How can I convert an image into Base64 string using JavaScript?

  1. A more straightforward approach: after completing step 2, simply provide the parsed JSON with all image URLs. Utilize these URLs to showcase assets like so:

    <img src={parsedJSON.someURL} />

Answer №2

Latest Update: Next.js now includes a convenient <Image /> tag for optimizing image loading with preloading and lazy loading features. Learn more about it here: https://nextjs.org/docs/api-reference/next/image

Here's an example of how to use it:

import Image from 'next/image'

...
..
.

<Image
    src={"the link of the image"}
    alt=""
    width="300"
    height="300"
/>

Answer №3

Why bother altering your NextJS application to handle downloading and re-uploading images when you can simply tweak the upload function in WordPress? By adjusting the upload function in WordPress, every time an image is uploaded, it will automatically be copied to your NextJS directory.

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

Searching in jquery not functioning as intended

Greetings! I'm in the process of creating a live search feature similar to what's demonstrated at this link. However, I've encountered a minor issue with this snippet of code: jQuery("#result").on("click",function(e){ var $clicked = $(e.ta ...

Submit a set of form variables to PHP using AJAX

I am attempting to transmit a set of form parameters to a PHP script for processing. In the past, I have achieved this using $.post, but now my goal is to accomplish it exclusively with $.ajax. Below is the jQuery click event designed to send all variabl ...

Associating models using a many-to-many relationship in Sequelize unexpectedly restricts the ability to modify attributes in the join table

I am in the process of incorporating a voting feature into my app, allowing users to vote on responses from other users. The backend of my Node app is built using Express and Sequelize. Currently, I am utilizing a SQLite database for testing convenience. ...

Why does Vue 3 refuse to refresh an <img> element, while it successfully refreshes all other components within the same component?

In my current Vue project, I have set up multiple link cards (<a class='card'></a>) inside a "deck" container (<div class='deck'></div>). The implementation for these elements is relatively straightforward: <s ...

Using JSON in Node.js

After recently diving into Node, I've been working on parsing JSON data from an API. While I have managed to access most of the JSON content, there are certain elements that seem to elude me. var request = require("request"); var url = 'https: ...

Error: The JSON data contains an unexpected token at the beginning Express

I am currently following a tutorial (here) to establish a connection between Express and React Native. I have a server.js script running which connects to the client (App.tsx) on my IP address using port 3000. The server and app are running simultaneously ...

Difficulty connecting? Troubleshooting error message 'net::ERR_NAME_NOT_RESOLVED' between Socket.io and

I have set up a Socket.io Server using UVICORN on my Windows 10 operating system and implemented the client side with Next.js and TypeScript. However, when attempting to connect to the socket.io server, I encountered the following errors: https://i.sstat ...

Is there a way to prevent pixels from being rendered outside of a designated rectangle in HTML5?

I'm looking to add screen-in-screen functionality to my HTML5 game, and I have an idea for how to approach it: //Function called every frame function draw(){ set a mask rectangle only draw pixels from the current frame that fall within this recta ...

Obtaining a value from a protractor promise within a function and returning it

Is there a way to extract text from a webpage and use it for asserting on another element in the specification? Here is a simple example that demonstrates how you cannot return a value from a function within a Protractor promise: describe('My Test&a ...

Can anyone tell me what I might be doing incorrectly when comparing these two timestamps?

I am facing an issue while comparing two timestamps in Angular. Here is the code snippet: public isAuthenticated(): boolean { const token = localStorage.getItem('Fakelife'); const lifetime = new Date().getTime(); const result = life ...

Routing static pages in Angular 2

I successfully created a static page using Angular 2. When I run ng serve and visit my page, it functions as intended. Specifically, I can navigate to a specific page by typing in the URL, such as www.mysite.com/resume. However, after uploading it to my si ...

What is the best way to combine a javascript onclick function with php?

I'm currently facing an issue with integrating the onclick function in PHP. Can anyone lend a hand? Here are my code snippets <html> <head> <title></title> <script language="Javascript"> function delete() { val del ...

Messages traced by log4javascript are not being displayed

I am currently utilizing log4javascript version 1.4.3. Everything in my application seems to be functioning correctly with all log levels except for trace. To simplify the troubleshooting process and ensure that the issue does not lie within my applicati ...

I am looking for the best way to sort my JSON data based on user roles before it is transmitted to the front end using Express and MongoDB. Any

I scoured the internet high and low, but to no avail - I couldn't find any framework or code snippet that could assist me in my predicament. Here's what I'm trying to achieve: whenever a response is sent to my front-end, I want to filter th ...

SFDC error: argument list missing closing parenthesis

I encountered an issue that states: "Missing ) after argument list" This problem arises when I attempt to click on a custom button within SFDC. The purpose of this button is to initiate a specific case type in both our Internal and Community environme ...

Does the component need to be re-rendered every time I visit the page, even if the data remains the same?

I'm trying to grasp the concept of how memo works with components. Here is a simple component that I have, which is static: const Home = memo((props: any) => { useEffect(() => { console.log('home changed'); }, []) ret ...

Configuring ESLint and Babel

Currently, I'm implementing ESLint into my project with the Airbnb style guide and Husky for pre-commit checks. Unfortunately, I encountered an issue where ESLint is flagging errors related to 'import/no-unresolved' when using path aliasing ...

Angular JS Tab Application: A Unique Way to Organize

I am in the process of developing an AngularJS application that includes tabs and dynamic content corresponding to each tab. My goal is to retrieve the content from a JSON file structured as follows: [ { "title": "Hello", "text": "Hi, my name is ...

The Java Selenium script encountered an illegal type error when trying to execute JavaScript through JavaScriptExecutor: driverFactory.CustomWebElement

I have a CustomWebDriver class that extends the functionality of JavascriptExecutor. Here is my implementation: @Override public Object executeScript(String script, Object... args) { return ((JavascriptExecutor) driver).executeScript(script, args); } ...

What is the most efficient method for swapping out a portion of an array with a different one in Javascript?

Currently experimenting with Dygraph and have successfully integrated a reloader feature that adds high-resolution data as users zoom in on the graph. To maintain the original file boundaries, I am preserving the existing data and inserting the newly load ...