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

Async Autocomplete fails to display options if the label keys do not match the filtering keys

While I have experience with ReactJs and Material UI, I encountered a surprising issue. I am using the Material-UI Autocomplete component as shown below. The users variable is an array of objects. When searching for firstName or lastName in the user table, ...

Error encountered: Required closing JSX tag for <CCol> was missing

Encountered a strange bug in vscode...while developing an app with react.js. Initially, the tags are displaying correctly in the code file. However, upon saving, the code format changes causing errors during runtime. For instance, here is an example of the ...

Guide on using JavaScript to extract and display a random text from a datalist upon clicking with the onclick event

Is there a way for a JavaScript function to select a random sentence from a datalist within the same file and display it upon clicking a button with an "onclick" event? I'm new to JavaScript and seeking the simplest solution. Can anyone provide an exa ...

HTML5 Audio using AudioJS may not function reliably when loaded remotely

I have been encountering frustrating issues with loading audio tags for a while now. Despite spending nearly two weeks trying to solve the problems, every fix seems to create another one. My webpage includes an < audio > tag that utilizes audio.js to m ...

Attempting to transfer information between components via a shared service

Currently, I am utilizing a service to transfer data between components. The code snippet for my component is as follows: constructor(private psService: ProjectShipmentService, private pdComp: ProjectDetailsComponent) { } ngOnInit() { this.psSe ...

Experiencing challenges with socket io connectivity between my backend and Quasar application. Encountering a 403 Forbidden error while trying to establish a connection with

I recently updated my Quasar app and ran into issues with the websocket connection after switching from development to production mode. The app is hosted on an Express server via pm2 on my Ubuntu server, which also connects to a database. Here are some sn ...

Saving data in multiple collections using MongoDB and Node.js: A comprehensive guide

In a recent project of mine, I have implemented a combination of nodeJS and mongodb. My main goal is to store data in multiple collections using just one save button. Below is the code snippet that I am currently working with: var lastInsertId; loginDat ...

Javascript datatables do not allow for setting a default column sort

I am encountering an issue where I need to sort the results by a specific column on page load. In this case, I want the initial results to be displayed in descending order based on "RecordDate". However, it seems that the server side is blocking any sort ...

Oops! SAPUI5 is encountering an issue with reading property '0' of undefined

Is there a possibility of encountering multiple errors leading to this specific error message? https://i.stack.imgur.com/RpWhw.png Despite searching online, it appears that the error occurs in the JavaScript file when getelementbyid returns null. However ...

Retrieve the exact value of a key within a string

This is my unique text: let x = "Learning new things every day!"; I am utilizing the substring() method to extract a specific part of it: console.log(x.substring(9, 12)); Instead of the entire string, I only want the word 'new'. let x = "l ...

Why is my database being accessed by my Prisma unit tests?

After following the Unit testing with Prisma guide, I wrote a unit test for a function that interacts with my database. Despite mocking the Prisma client as suggested in the guide to prevent database calls, when I run the test, data is actually created in ...

Utilizing JavaScript to retrieve data from a self-submitting form

From my database, I am able to create a list of options for users to choose from. Once a selection is made, the values are submitted back to the same page and retrieved using Javascript. Within the same form, there are radio buttons and a multiple selecti ...

Sort columns in a MUI datatable

I am facing an issue with sorting in a column that represents an object. Although I can display the desired value, the sorting functionality does not seem to work for that particular column. Here is an example to provide better clarity: const [data, set ...

Effectively accessing the Templater object within a user script for an Obsidian QuickAdd plugin

I have developed a user script to be used within a QuickAdd plugin Macro in Obsidian. The Macro consists of a single step where the user script, written in JavaScript following the CommonJS standard, is executed. Within this script, there is a task to gene ...

Tips for using multiple Angular directive modules in PprodWant to enhance your Pprod experience by

Currently, I am working on jhipster Release 0.7.0 and our jhipster app has multiple types of directive modules – one for the index page and another for common directives. However, when we run the app on Prod profile, an exception occurs: [31mPhantomJ ...

Navigate through the Jquery slider by continuously scrolling to the right or simply clicking

Is there a way to prevent my slider from continuously scrolling? I think it has something to do with the offset parameter but I'm having trouble figuring it out. Any assistance would be greatly appreciated. var $container = $(container); var resizeF ...

There seems to be a syntax error in the AngularJS/Bootstrap code, with an unrecognized expression

Hey there, I'm currently working on developing an application using Angular and Bootstrap. I've successfully implemented ui.router for routing purposes, but I've encountered an issue when loading the Bootstrap library. The console is showing ...

Oops! An error occurred: fs.readFileSync is not a valid function to perform the Basic

I'm facing a dilemma - I have a relatively simple app (I'm still new to Node): App.js import * as RNFS from 'react-native-fs'; var config_full; // readFile(filepath: string, encoding?: string) RNFS.readFile('./config.toml', ...

Can anyone suggest methods for displaying query data from a JSON file using HTML?

After countless hours of searching through various forums, I have attempted numerous methods to display query data from a JSON file onto an HTML page. My initial attempt was using XmlHttpRequest, which yielded no results. I then tried utilizing jQuery, sp ...

Is there a way to achieve horizontal alignment for the Twitter and Facebook buttons on my page?

By utilizing the html code provided, I successfully incorporated Twitter and Facebook "Like" buttons into my website. Initially, they were stacked vertically, which resulted in excessive use of vertical space. To optimize space usage, I decided to align th ...