Get hands-on experience with 20+ free Google Cloud products and $300 in free credit for new customers.

Can't create BigQuery query jobs in nextjs project

Someone please help me , i'm desperate and I'm just a coop student working for a startup... being stucked for 2 days.

I'm writing my next.js application and i need to fetch some data from the BigQuery... I've tried using ADC, service account, but i just can't create a simple query job.... i can run the query job from command line using service account key, but my code won't work .  The console logs  would stop at 'Creating Query Job' ... I've read all the documents i can possibly find😩

Server side

export default async function fetchBigQuery(req: NextApiRequest, res: NextApiResponse) {
console.log('fetchBigQuery invoked::', req.method)

if (req.method !== 'GET') {
res.status(405).end() // Method not allowed
return
}

const options = {
keyFilename: '/path/to/service-acct.json',
projectId: 'project-dev',
}

const bigquery = new BigQuery(options)

const query = `SELECT * FROM alter-prime-dev.client_dmo_mar.out_dmo_mar_climate_hazards__assets LIMIT 10`

console.log('did it get to here')

try {
console.log('Creating Query Job')
const [job] = await bigquery.createQueryJob({ query:query })
console.log('Job Created:', job.id)

console.log('Getting Query Results')
const [rows] = await job.getQueryResults()
console.log('Query Results:', rows)


if (rows.length === 0) {
return res.status(200).json({ message: 'No data found' })
}
return res.status(200).json({ rows }) // Return the rows as a JSON response
} catch (error) {
return res.status(500).json({ error: 'BigQuery error' })
}
}

  front end

'use client'

import { useEffect, useState } from 'react'

const NamesComponent = () => {
const [names, setNames] = useState<string[]>([])

const queryBigQuery = async()=>{
console.log('About to fetch data') // Debugging line
try {
const res = await fetch('/api/fetchBigQuery', {
method: 'GET',
headers: { 'Content-Type': 'application/json' },
})

if (res.ok) {
const jsonData = await res.json()
console.log('Fetched Data:', jsonData) // Debugging line to view fetched data
setNames(jsonData) // Update the state with fetched data
} else {
console.error(`Error: ${res.status}`)
}
} catch (error) {
console.error('Failed to fetch user data:', error)
}
}

useEffect(() => {
queryBigQuery()
}, [])

return (
<div>
<h1>Fetched Data:</h1>
<pre>{JSON.stringify(names, null, 2)}</pre>
</div>
)
}

export default NamesComponent
0 3 921
3 REPLIES 3