0

I have an API that returns to me raw html. I want to extract some specific information. I was using Jquery in the past to do so :

fetch(url)
    .then((html) => {
       const parsed = $(html)
       return parsed.find(id).attr('src')
    })

something like that.

Now that I moved to NextJs, I want to do this operation at compile time to do server rendering. In this function:

export async function getStaticProps({ params }) {
    const data = await getData(params.slug)
    return { props: { data } }
}

I encountered a first problem where jquery needs a window. I solved it by using this code:

const jsdom = require('jsdom')
const $ = require('jquery')(new jsdom.JSDOM().window)

For someone that is encountering this problem too, I first had to resolve a module missing: canvas. I solved this by adding:

webpack: (config, { webpack }) => {
    config.plugins.push(new webpack.IgnorePlugin(/canvas/, /jsdom$/))
    return config
},

to my next.config.js.

But now I have a problem when I do: $(html), it says that $ is not a function.

I tried this:

const jsdom = require('jsdom')
const window = new jsdom.JSDOM().window
window.document.body.innerHTML = html
const parsed = require('jquery')(window)

parsed.find(id).attr('src')

but now I get parsed.find(id).attr is not a function.

Anyone could help ?

Thank you very much.

Wonay
  • 1,160
  • 13
  • 35
  • Does this answer your question? [How do I parse a HTML page with Node.js](https://stackoverflow.com/questions/7372972/how-do-i-parse-a-html-page-with-node-js) – juliomalves Jul 19 '21 at 17:35
  • Hello @juliomalves , it does not because I am using Netlify so I don't have access to server side code. Only the pre-rendered method from NextJS – Wonay Jul 20 '21 at 12:58
  • 1
    `getStaticProps` runs on the server in a Node.js environment. – juliomalves Jul 20 '21 at 13:04

0 Answers0