Strapi CronStrapi Cron

Creating a cron in Strapi for adding short links to articles

I was searching for a service to shorten my URLs for social sharing links and found which offer a free plan with perfect rest API.

There can 2 approaches to add a corn job in Strapi:

  • Use Strapi native cron feature (which I failed to run after multiple attempts)
  • Use OS crontab and configure cli based jobs outside Strapi (the approach I am using for my URL shortener cron)
  1. Create a CLI command in Strapi

    • Install node sdk
    yarn add
    npm install
    • Add required configurations in .env file:
    # your short domain
    # your short domain id
    # your API key with all access
    # your website base URL to be shortened
    • Create a command file in your strapi project (Ex: /home/ubuntu/strapi/cli/shortener.js):
    #!/usr/bin/env node
    const strapi = require('strapi');
    if (process.env.CRON_URL_SHORTENER) {
        async (instance) => {
          // fetch articles to add short URL for mongo db (refer to strapi documentation in references for MySQL query)
          const articles = await instance.query('article').model.find({
            shortUrl: null,
            published_at: {$ne: null}
          }, ['slug', 'shortUrl']);
          if (articles.length > 0) {
            const shortio = require("");
            const short = new shortio(process.env.URL_SHORTENER_DOMAIN, process.env.URL_SHORTENER_DOMAIN_ID, process.env.URL_SHORTENER_API_KEY);
            for (const article of articles) {
              let link = await short.createLink({originalURL: process.env.URL_SHORTENER_BLOG_URL + article.slug});
              // secureShortURL: '',
              if (link && link.secureShortURL) {
                console.log("slug:", article.slug);
                console.log("shortUrl:", link.secureShortURL);
                const result = await instance.query('article').model.updateOne(
                  {$set: {"shortUrl": link.secureShortURL}}
          console.log("url added:", articles.length);
          // exit with 0 code
    • Make shortener.js executable:
    sudo chmod +x shortener.js
    • Add the command to your Strapi project package.json as shortener:
      "name": "api-cms-adapttive-com",
      "private": true,
      "version": "0.1.0",
      "description": "A Strapi application",
      "scripts": {
        "develop": "strapi develop",
        "start": "strapi start",
        "build": "strapi build",
        "strapi": "strapi",
        "shortener": "node cli/shortener.js"
  2. Setting the CLI command in crontab

    • Create log folder and file
    mkdir -p /var/log/strapi
    touch /var/log/strapi/cron.log
    • Add command in os crontab
    crontab -e
    • Copy and paste the below in crontab:
    0 8 * * * export CRON_URL_SHORTENER=1 && cd /home/ubuntu/strapi && yarn shortener |& tee -a /var/log/strapi/cron.log