Concealing URL in client-side fetch request within Next.js

A contact form built in Next.js makes use of the FormSubmit API to send emails upon clicking the submit button. Below is the code for the onSubmit handler:

const handleSubmit = async (e) => {
  e.preventDefault();
  const res = await fetch("https://formsubmit.co/ajax/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3b42554c4759614a40484d0f424e4c">[email protected]</a>", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      Accept: "application/json",
    },
    body: JSON.stringify({
      name: "FormSubmit",
      message: "I'm from Devro LABS",
    }),
  })
    .then((response) => response.json())
    .then((data) => console.log(data))
    .catch((error) => console.log(error));
};

The issue here is that the fetch request URL

https://formsubmit.co/ajax/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8df6e2fefdcfebe1f9fee7bfdac9fff5fffa8bf6faf8">[email protected]</a>
can be seen on the client side through DevTools when the request is made. I am trying to find a way to hide this URL in Next.js, but have not been successful yet. Is there a solution to address this concern?

Answer №1

While the original request cannot be hidden from the browser, there is a workaround using an API route to conceal the URL of the external service.

To achieve this, set up an API route (e.g., /api/submit-data) that makes a call to

https://formsubmit.co/ajax/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="453c2a3037052028242c296b2628">[email protected]</a>
, serving as a proxy for the actual service.

// /pages/api/submit-data
export default async function handler(req, res) {
    if (req.method !== "POST") {
        res.setHeader('Allow', ["POST"])
        return res.status(405).end(`Method ${req.method} Not Allowed`)
    }

    try {
        const response = await fetch("https://formsubmit.co/ajax/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b8c1d7cdcaf8ddd5d9d1d496dbd7d5">[email protected]</a>", {
            method: "POST",
            headers: req.headers, 
            body: req.body 
        })
        const data = await response.json()
        res.status(200).json(data)
    } catch(e) {
        res.status(500).end(`An error occurred: ${e}`)
    }
}

Instead of directly calling the external service from the client-side, send requests to the newly created API route.

const handleDataSubmit = async (event) => {
    event.preventDefault();
    await fetch("/api/submit-data", {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
                Accept: "application/json"
            },
            body: JSON.stringify({
                name: "FormSubmit",
                message: "I'm submitting data through Devro LABS"
            })
        })
        .then((response) => response.json())
        .then((data) => console.log(data))
        .catch((error) => console.log(error));
};

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

Examining the version of a node module installed in the local environment and comparing it

One of the reasons I am asking this question is because I have encountered challenges while collaborating with other developers. At times, when other developers update node module versions, I forget to install these new modules after pulling the latest co ...

What is the best method for transferring properties to the parent component using Vue router?

I have a multi-step form that each step has a different header structure. The only variation in the header among the steps is the wording, which changes as you progress through the steps. I am looking for a way to achieve this using Vue Router: pa ...

JavaScript: selecting multiple elements with identical attributes

I'm struggling to target all a tags with the 'data-caption' attribute. I attempted to do this by: first selecting all the a tags let links = document.querySelectorAll('a'); and then trying to access their attributes links.get ...

Prisma query that selects categories only if they are linked to an item in a table relation

I am managing two tables, one called categories and the other called items. The categories table is structured like this: model publish_categories { c_id Int @id @default(autoincrement()) name String slug String active Int? } In the items ...

Guide to utilizing exact matching functionality in ExpressJs router

In my ExpressJs application, I have defined two routes like so: router.get("/task/", Controller.retrieveAll); router.get("/task/seed/", Controller.seed); When I make a request to /task/seed/, the Controller.retrieveAll function is call ...

The jQuery plugin embedded in the Joomla 3.2 module fails to load or function properly

Seeking help with a JavaScript issue on my Joomla website. I'm not an expert, so please bear with me. I am using a regular plugin (not a Joomla specific one) to display my portfolio. It should work like this: ... black.html This is how it shouldn&a ...

Styling with CSS: A guide to reducing paragraph margins within a div element

My current project involves using javascript to dynamically insert paragraphs inside a div element. Essentially, the script grabs the value entered into an input form when a button is clicked and adds it as a new paragraph within a specific div. However, I ...

Decide on the javascript/jquery libraries you want to include

My app is experiencing slow loading times on the home screen and students using it from school district computers are running into ERR_CONNECTION_RESET errors due to strict firewalls. The excessive loading of javascript and jquery libraries in the head of ...

Error encountered while updating in the midst of an ongoing state transition, e.g. within the `render` method

class MyComponent extends React.PureComponent { constructor(props) { super(props); this.state = { obj: [], externalObj: [], }; } fetchData = (external) => { ... arr = arr.filter(a => a.toLowerCase().includes(&ap ...

In Node JS, the variable ID is unable to be accessed outside of the Mongoose

When working with a Mongoose query, I encountered an error where I am trying to assign two different values to the same variable based on the query result. However, I keep getting this error: events.js:187 throw er; // Unhandled 'error' ev ...

Executing a protractor test on Safari results in the message "Angular was not located on the webpage https://angularjs.org/"

Recently, I encountered an issue while trying to run a Protractor test on Safari, even when following the official example provided at http://www.protractortest.org/. Below are my conf.js and todo-spec.js files. The problem arises when I set browser.ignor ...

What is the best way to convert a Date into the JSON format before sending it to the database?

I'm currently delving into backend development with Node.js, and I am in the process of connecting my backend to a MongoDB. Specifically, I am working on creating a User object that includes Birth Date as one of its properties. However, I am strugglin ...

Is there a way to retrieve the response body in Express framework?

In my NodeJS API using Express, I am attempting to save the response body of a request. To achieve this, I have created two middleware functions. app.use((req, res,next) => { res.status(404).json({ errors: [{ field: "url", ...

Govern Your Gateway with Expressive Logs

I'm facing some issues with the logs in my Express Gateway: Although I followed the documentation and enabled Express Gateway logs, I cannot locate any log files under my gateway root directory. Whenever I start the gateway using the command LOG_L ...

Cloud Firestore trigger fails to activate Cloud function

I am facing an issue with triggering a Cloud Function using the Cloud Firestore trigger. The function is supposed to perform a full export of my sub collection 'reviews' every time a new document is added to it. Despite deploying the function suc ...

"Facing an issue with Google Chrome not refreshing the latest options in an HTML select dropdown list

Having trouble creating an offline HTML file that incorporates jQuery for the script. The page features a state select menu followed by a second menu for counties. When a state is selected, only the corresponding counties should display while others remai ...

Retrieving and storing information from a form without the need to submit it

I have been given the task of creating a load/save feature for a complex form. The goal is to allow users to save their progress and resume working on it at a later time. After much consideration, I have decided to implement server-side storage by saving ...

React Weather App experiencing issues with prop communication and updating variables

My innovative weather app allows users to input custom longitude and latitude coordinates. Once the coordinates are received, they are passed as props to a child component where they are used in an API call to fetch data for that specific area. While ever ...

Revamp the angular design of the mat-tree UI bottom border line issue

Can you help me with changing the direction of the mat tree from right to left? I need to remove the bottom border, please refer to the image here ...

JavaScript in Internet Explorer is showing an error message stating that it is unable to access the property '0' of an undefined or null

JavaScript Code function update() { var newAmt = 0; var newtable = document.getElementById("tbl"); for ( var i = 0; i < newtable.rows.length; i++) { innerTable = newtable.rows[i].cells[0].childNodes[0]; if ( (innerT ...