0
votes

I am trying to use recaptcha with sapper, actually I dinamically load the recaptcha CDN in the onMount event of svelte, upto here everything is working well:

enter image description here

but I need to load the reCAPTCHA site key from the server side, something like a .env file, but I cannot find the way to do this from the official documentation, there is an official way to load information into the components from the server side in sapper?

1

1 Answers

3
votes

You're not loading the key from the server side, because it's running in the client. The key needs to be present in the client-side JavaScript bundle. The easiest way to include it is by configuring the replace plugin (if you're using Rollup) or the DefinePlugin (in webpack).

In Rollup, update this block in the config:

replace({
  'process.browser': true,
  'process.env.NODE_ENV': JSON.stringify(mode),
  'process.env.RECAPTCHA_KEY': my_recaptcha_key
})

In webpack, update this block:

new webpack.DefinePlugin({
  'process.browser': true,
  'process.env.NODE_ENV': JSON.stringify(mode),
  'process.env.RECAPTCHA_KEY': JSON.stringify(my_recaptcha_key)
})

Then, you can refer to that value in your code:

script.src = `https://www.google.com/recaptcha/api.js?render=${process.env.RECAPTCHA_KEY}`;

In future, please avoid using screenshots to provide code samples — use markdown instead. It makes pages more searchable, more accessible to people using assistive technology, and means that people can copy and paste the code instead of having to retype it.