Skip to content

Instantly share code, notes, and snippets.

@jorgemasta
Last active October 13, 2023 23:01
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jorgemasta/041fb3f87c1d754439032d508ca83353 to your computer and use it in GitHub Desktop.
Save jorgemasta/041fb3f87c1d754439032d508ca83353 to your computer and use it in GitHub Desktop.
Add `BIGCOMMERCE_STOREFRONT_API_TOKEN` to `.env`
import fs from 'fs'
import axios from 'axios'
const { REACT_APP_API_ENDPOINT, BIGCOMMERCE_STORE_HASH, BIGCOMMERCE_STORE_API_TOKEN } = process.env
// REACT_APP_API_ENDPOINT=http://localhost:3030
// BIGCOMMERCE_STORE_HASH=WQiOjEsImN
// BIGCOMMERCE_STORE_API_TOKEN=FsaG9zdDozMDMwIl0sImVhdCI6MTdww3
const [host] = REACT_APP_API_ENDPOINT.split('/api')
const expiresAt = parseInt(Date.now() / 1000 + 3600 * 24 * 365, 10)
axios(
`https://api.bigcommerce.com/stores/${BIGCOMMERCE_STORE_HASH}/v3/storefront/api-token`,
{
method: 'POST',
headers: {
'content-type': 'application/json',
'x-auth-token': BIGCOMMERCE_STORE_API_TOKEN,
},
data: {
channel_id: 1,
expires_at: expiresAt,
allowed_cors_origins: [host],
},
}
)
.then((response) => {
const newEnvVar = `BIGCOMMERCE_STOREFRONT_API_TOKEN=${response.data.data.token}`
return fs.readFile('.env', 'utf8', (err, data) => {
const lines = data.split('\n')
const without = lines.filter(
(line) =>
!/^BIGCOMMERCE_STOREFRONT_API_TOKEN=/.test(line) && line !== ''
)
const newLines = [...without, newEnvVar].join('\n')
fs.writeFile('.env', newLines, () => {
console.log(newLines)
})
})
})
.catch((error) => {
if (error) throw new Error(error)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment