Ad

Next.js - Using BigQuery Client Library Gives An Error : Module Not Found: Can't Resolve 'child_process'

I am trying to query bigQuery dataset from a next.js project.

I have installed @google-cloud/bigquery and followed the steps from here I have also tried next.js related solutions from this link but still getting below error.

It looks like next.config.js needs to be configured for this to allow this api call. I am not sure what needs to be changed.

Could someone please help me resolve this issue?
here is my code :

const { BigQuery } = require("@google-cloud/bigquery");
const bigquery = new BigQuery();

  useEffect(() => {
    async function queryBigQuery() {
      const query = `
      SELECT fieldname
      FROM \`db.dataset.tablename\` WHERE columnname = 50 
      LIMIT 10`;

      const options = {
        query: query,
      };

      // Run the query
      const [rows] = await bigquery.query(options);

      console.log("Query Results:");
      rows.forEach((row) => {
        const url = row["url"];
        const viewCount = row["view_count"];
        console.log(`url: ${url}, ${viewCount} views`);
      });
    }

    queryBigQuery();
  }, []);

**wait  - compiling...
error - ./node_modules/google-auth-library/build/src/auth/googleauth.js:17:0
Module not found: Can't resolve 'child_process'**

UPDATED:

I am able to load bigQuery library I think on client side but its giving me new error. Here is my latest next.config.js file

module.exports = {
  webpack: (config, { isServer, webpack }) => {
    if (!isServer) {
      config.node = {
        dgram: "empty",
        fs: "empty",
        net: "empty",
        tls: "empty",
        child_process: "empty",
      };
    }

    return config;
  },
  env: {
   project variables. 
};

New Error:

enter image description hereenter image description here

Ad

Answer

@google-cloud/bigquery is meant to run on a Node.js environment, it won't work in the browser.

You'll need to move your code to a data fetching method like getStaticProps/getServerSideProps or to an API route, as they all run server-side.

Here's an example using an API route, as it seems to fit your use-case best.

// pages/api/bigquery

const { BigQuery } = require("@google-cloud/bigquery");
const bigquery = new BigQuery();

export default function handler(req, res) {
    const query = `
        SELECT fieldname
        FROM \`db.dataset.tablename\` WHERE columnname = 50 
        LIMIT 10
    `;

    const options = {
        query: query,
    };

    // Run your query/logic here

    res.json(data); // Return your JSON data after logic has been applied
}

Then, in your React component's useEffect:

const queryBigQuery = async () => {
    const res = await fetch('api/bigquery');
    const data = await res.json(); // Returns JSON data from API route
    console.log(data);
}

useEffect(() => {
    queryBigQuery();
}, []);
Ad
source: stackoverflow.com
Ad