Preview Content Instantly

With Contentstack, you can set up a system that'll enable you to preview content changes instantly. When you save an entry, it will get auto-published on a specified environment such as "pre-prod", "staging", and so on.

After the entry is auto-published, the page will auto-refresh itself allowing you to view your changes instantly. The advantage of this setup is that you don't have to manually publish the entry or refresh the page. It happens automatically.

In this document, we'll discuss the steps required to set up such a system.

Brief overview of the process: When a user clicks on the Save button, a webhook is triggered which invokes the AWS Lambda Function. The Lambda Function then publishes the content on the specified environment, such as "pre-prod" or "preview". When the content is published, another webhook is triggered via the web application. This notifies Pusher to send real-time reload request for the page that's being edited, letting you preview your content changes instantly.

Pre-requisites

  • Contentstack account
  • An account with Pusher and some working knowledge of it
  • Access to the AWS Lambda environment and basic understanding of how to work with it

To accomplish this, we will divide the task in two sections:

Let's discuss the steps in detail.

Auto-publishing an Entry

In the following steps, we'll set up a system that'll auto-publish an entry using AWS Lambda when the entry is saved.

  1. Create a Stack Management Token

    1. Log in to your Contentstack account, click on the Settings icon and select Tokens.
    2. On the Tokens screen, select Management Tokens.

      Management Tokens.jpg

    3. It will ask you to create a management token, select + ADD TOKEN.
    4. Provide a suitable name to your token, for example, "My Token" and an optional description.
    5. Under Permissions, select Read and Write as we require both permissions to perform our tasks.
    6. You can select the Expiry date for your management token. So choose either Never or a specific Date.
    7. Click on Generate Token and your management token will be generated.

    Note: The Management Token will be visible on the dialog that appears. It will not be visible once you close the dialog, so make a note of your management token for future reference. Read more about Management Tokens.

  2. Set up an AWS Lambda and API Gateway

    1. Login to your AWS Management Console, select AWS Lambda Service from the service list.
    2. Click on the Create Function button, and then the Author from Scratch option.
    3. Configure the Lambda based on your requirements. Choose Node.js as your run-time language and click the Create Function button to create the function.

      Note: You can use any language instead of Node.js. You can also add triggers to your lambda to push an event when the lambda is invoked.

    4. AWS Lambda offers an inline code editor. You can write your lambda code here or alternatively upload the code. We have created a sample code for this exercise which is available on our GitHub page. Download the index.zip file and start using it.
      Index file.jpg
    5. After downloading the index.zip file, upload it on Lambda. It should look like this:
      uploaded code.jpg
    6. Next, we need to set the Environment variables as shown below:
      CONTENTSTACK_STACK_MANAGEMENT_TOKEN= Your Stack Management token
      CONTENTSTACK_STACK_API_KEY= Your Stack API Key
    7. Review your setting and click on the Save option if everything you entered is correct.
    8. Now create the API Gateway by navigate to + Add trigger > API Gateway > Create new API > select Rest API > click on the Add button. This step will generate the URL which you will add to configure webhooks in Contentstack.

    With this, we have set up the Lambda Function to publish the entry on the specified environment when it is saved.

  3. Create a Webhook for Save Events

    Next, we will create a webhook for capturing the entry save events. Proceed as follows:

    1. Create a webhook by navigating to the Settings icon > Webhooks > + New Webhook.
    2. Enter any valid name for your webhook, for example, Instant Preview.
    3. In the URL to notify field, enter the AWS Lambda URL, where the webhook will notify about the save events.
    4. Under the Custom header option, enter parameter as target_environments. As value, enter a comma separated list of environments where you will publish the content, for example, stage, pre-prod, and so on.
    5. Under the When section, inside Conditional View, add the conditions to trigger when all entries of any content type are created or updated:

      First Webhook.jpg

    With this, we have completed the basic setup to execute our first task — publishing an entry. Now create and save your entry. As soon as you save your entry, AWS Lambda will publish it on your specified environment such as "staging", "pre-prod", or "preview".

Auto-reloading the Page

Let's now move ahead and set up a system for auto-reloading the page when the entry is saved and published by AWS Lambda.

  1. Create a Pusher Channel Account

    For our example, we'll use Pusher which is a hosted service. By using Pusher, we'll be able to add real-time bi-directional functionality via WebSockets (with HTTP-based fallbacks) to our mobiles or web applications.

    Pusher also allows us to apply filters to better control the way messaging is handled. Many organizations use Pusher to create live activity streams where feeds get updated in real time. Other examples include live chats, score updates, real-time stock updates, live data visualizations, and so on. 

    For our example, we will use Pusher to let users see the content previews real-time when they save an entry. For that, we will need to set up an account with Pusher. Let's follow the below steps:

    1. Log on to the Pusher sign up page and create an account.
    2. It'll ask you to create a Channel. Provide the details and your create your channel.
    3. You will get "app_id", "key", and "secret". Make a note of these credentials. You will require them when you configure your app.

    This will enable your app to communicate with Pusher using the keys, so that Pusher can generate content previews instantly.

  2. Update the Existing Website Code

    The next step is to install Pusher and configure it in you web app code. Execute the following steps at the Server Side:

    1. Install pusher.js by using the following command:
      npm install pusher --save
    2. Next, we need to setup realtime.js. To do this, create a realtime.js file inside you lib folder to manage real time events through the Pusher Server API. You will get the Pusher config from your Pusher account App Keys section:
      const Pusher = require('pusher');
      
      const pusher = new Pusher({
      
          appId: 'APP_ID',
      
          key: 'APP_KEY',
      
          secret: 'APP_SECRET',
      
          cluster: 'APP_CLUSTER'
      
      });
      
      const broadcast = (channel, event, data={}) 
      
        => pusher.trigger(channel, event, data);
      
      module.exports.broadcast = broadcast;
    3. The next step is to update the webhook route to broadcast any "publish" event on channel with name set to the UID of the published entry. Set up Contentstack Webhook to call the webhook route on entry publish of any contenttype of the respective environment as follows:
      const broadcast = require('../lib/realtime').broadcast
      
      app.post('/webhook', function(req, res){
      
          res.header("Content-Type", "text/plain");
      
          res.header("statusCode", "200");
      
          res.set("Connection", "close");
      
          res.status(200)
      
          res.send('success')
      
          broadcast(req.body.data.entry.uid, 'publish')
      
      })
    4. The last step is to make the Client Side changes. Include the Pusher client library in your client site using the chrome extension as shown below:
      <script src="https://js.pusher.com/4.3/pusher.min.js"></script>
      Add the following JavaScript snippet to client side which will listen for publish events on channel with entry UID as name:
      var pageRef = document.body.getAttribute('data-pageref');
      
      var pusher = new Pusher("APP_KEY", {
      
            cluster: "APP_CLUSTER",
      
            forceTLS: true
      
      });
      
      var channel = pusher.subscribe(pageRef);
      
      channel.bind("publish", function(data) {
      
          location.reload();
      
      });

    With these steps, you have configured Pusher in you web app.

  3. Create a Webhook for Auto-refreshing the Page

    1. Create a webhook by navigating to the Settings icon > Webhooks > + New Webhook.
    2. Enter any valid name for your webhook, for example, Instant Preview.
    3. In the URL to notify field, enter your app's URL where your app is deployed, where the webhook will notify about the save events.
    4. In the When section, inside the Conditional View, add the conditions as shown below:

      Second Webhook.jpg

    So now when any entry is published on the specified environment successfully, Pusher will auto-refresh the page letting you preview the changes instantly.

On This Page

top-arrow