So I'm running an app with nodejs + express, and trying to connect to the prismic API. The documentation is using the ESM, but I want to do it using CommonJS, when I finished the config and tried to run the app, I got the error getFirst is not a function, and I am suspecting that could be in the way I declared the export client to "module.export.client". But because I am not familiar with this so I am not 100% sure.
So at the moment my app.js file looks like this
require('dotenv').config()
const express = require('express')
const app = express()
const path = require('path')
const port = 3000
const client = require('./config/prismicConfig.js')
//Prismic
const prismic = require('@prismicio/client')
const prismicH = require('@prismicio/helpers')
const fetch = require('node-fetch')
const repoName = 'my-repo-name'
const accessToken = process.env.PRISMIC_ACCESS_TOKEN
const endpoint = prismic.getEndpoint(repoName)
const routes = [
{
type:'page',
path:'/'
}
]
module.exports.client = prismic.createClient(endpoint, {
fetch,
accessToken,
routes,
})
//Prismic
// template engine
app.set('views', path.join(__dirname,'views'))
app.set('view engine', 'pug')
//Middleware
app.use((req, res, next) => {
res.locals.ctx = {
prismicH,
}
next()
})
//end
app.get('/', async (req, res) => {
const document = await client.getFirst()
res.render('page', { document })
})
app.listen(port, ()=>{
console.log(` Example listen to http://localhost:${port}`)
})
And this is my prismicConfig.js
require('dotenv').config()
console.log(process.env.PRISMIC_ENDPOINT, process.env.PRISMIC_CLIENT_ID)
const fetch = require ('node-fetch')
const prismic = require ('@prismicio/client')
const repoName = 'my-repo-name'
const accessToken = process.env.PRISMIC_ACCESS_TOKEN
const endpoint = prismic.getEndpoint(repoName)
const routes = [
{
type: 'page',
path: '/',
},
]
module.exports.client = prismic.createClient(endpoint, {
fetch,
accessToken,
routes,
})
So I will appreciate an advice on this. In advance thank you for reading me :)
As you stated in your post, you're not using the default export, but a named export module.exports.client
in prismicConfig.js.
Which means that the consumer of this module, app.js, needs to destructure the client
property :
const { client } = require('./config/prismicConfig')