How to Create a Preview Button in Strapi v3 for Next.js

Quadri Sheriff, an aspiring technical writer, software programmer, and Amir Tadrisi, a full-stack engineer who love the challenges of working with cutting-edge technologies both wrote great articles; Implementing Previews with Next Applications using a Strapi backend & How to use Image and preview in your Nextjs - Strapi blog about using the preview system of Next.js with Strapi.


This is a companion discussion topic for the original entry at https://strapi.io/blog/create-a-preview-button-in-strapi-v3-for-next-js?utm_campaign=Strapi%20Blog&utm_source=email&utm_medium=strapiweekly&utm_term=logbook9&utm_content=logbook9

Nice article and perfect timing for me personally.

Can I ask how you are loading the environment variables in /ExternalLink.js?

When I use process.env.CLIENT_PREVIEW_SECRET and process.env.CLIENT_URL both of them return undefined.

I checked your github source of the FoodAdvisor app and you are not loading the env variables on the index.js file anywhere.

Every day is a learning day at Strapi :slight_smile:

I have found the solution to load .env variables for this preview link…

Please refer to the following discussions:

Essentially, we cannot load .env variables into the “frontend” of Strapi (the frontend includes plugins and extensions are plugin extensions).

Therefore we have to customise webpack.

Create a file ./admin/admin.config.js with the folllowing:

module.exports = {
    webpack: (config, webpack) => {
        const definePlugin = new webpack.DefinePlugin({
            CLIENT_URL: JSON.stringify(process.env.CLIENT_URL),
            CLIENT_PREVIEW_SECRET: JSON.stringify(
                process.env.CLIENT_PREVIEW_SECRET
            ),
        });
        config.plugins.push(definePlugin);
        return config;
    },
};

Then do following:

  1. delete the ./build and ./cache folders.
  2. yarn build --clean

Now you will be able to access CLIENT_URL and CLIENT_PREVIEW_SECRET in ./extensions/admin/src/InjectedComponents/ExternalLink/index.js