How to execute server side code with data from the client in next.js

I want to get the meta data from a URL the user enters in my Next.js application.

I’m using metadata-scraper to do this.

At the moment when the user submits the form my application fails with error:

Module not found: Can’t resolve ‘dns’

I did some research and this question implies that the issue is because i’m trying submitting server side code on the client, which makes sense. I’m unclear though how I could pass the url the user enters on the page to the server and return the metadata.

Here is my code

import { useState } from 'react';
import Input from '@/components/ui/Input';
import Button from '@/components/ui/Button';

const tree = () => {
  
  const [loading, setLoading] = useState(false);
  const [url, setUrl] = useState('');

  const handleFindUrl = async (e) => {
    e.preventDefault();
    
    const getMetaData = require('metadata-scraper')
    const link = url

    getMetaData(url).then((data) => {
      console.log(data)
    })
  };  

  return (
    <section className="bg-black mb-32 mx-auto max-w-6xl px-6">
      <form onSubmit={handleFindUrl} className="flex flex-col space-y-4">
        <Input
            type="text"
            placeholder="Link"
            value={url}
            onChange={setUrl}
            required
            />
            <Button 
                variant="slim" 
                type="submit" 
                loading={loading}>
                Sign up
            </Button>
        </form>
    </section>
  );
}

export default tree;

Answer

You’re saying you’ve many users who put URLs and data from that site will automatically be fetched. But this can’t be possible. You can’t do this all entirely from the front-end.

It’s basically happening because You have the script that makes some request to another website and the browser blocks your Cross-Origin request to that website/URL.. The main reason, a browser blocks this type of request is because of specter security vulnerability. Third-party requests to a website could allow an attacker to read what’s memory in the client’s device. That’s why this is not possible.

But You can do this with Cloud Functions. And use useEffect or useFetch with your API. That’s work very fine to get your data .