search help

Whenever you run an Apify actor, the system automatically creates an unnamed key-value store that can be used to get and set data related to the run simply by calling the Apify.getValue  and Apify.setValue functions provided by the apify NPM package. However, sometimes you might want to store data to or fetch data from a named key-value store that is shared between multiple runs of the actor or between multiple actors. Another advantage of named storage is that it persists forever. In this tutorial, you'll learn how to do that. 

You can achieve that by using the Apify.openKeyValueStore function.

First, let's create the named Key-value store.

const Apify = require('apify');

Apify.main(async () => {
// We will create a named store called MY-STORE
  const store = await Apify.openKeyValueStore('MY-STORE');

  // Rest of code here
});

Now, every method we call on the store will affect the selected named store. For example, you can get a record by calling:

const data = await store.getValue('My-key');


Example:

In this example, let's say we have an actor to send emails whenever necessary, e.g. if the website content has changed. We want to avoid repeated sending of the same emails, so we store the state of the sending to a key-value store named 'Emails' in a record with the key 'STATE':

const Apify = require('apify');

Apify.main(async () => {
  const store = await Apify.openKeyValueStore('MY-STORE');
 
  const previousState = await store.getValue('STATE');

// If the state was already present, we use it. Otherwise, we initialize it into empty object
const state = previousState || {};
});

We do our magic in between: check for repeated records, remove unwanted ones, format...
And finally, we set a nextState as the next record in our store.

const Apify = require('apify');

Apify.main(async () => {
const store = await Apify.openKeyValueStore('MY-STORE');

const previousState = await store.getValue('STATE');

// If the state was already present, we use it. Otherwise, we initialize it into empty object
const state = previousState || {};
});

  // Magic here...
 
  // It is a good practice to copy objects instead of
  // overwriting them. Weird things can happen otherwise.
  const nextState = Object.assign({}, state, stateChanges);
 
  await store.setValue('STATE', nextState);
});

And that's it.

Did this answer your question?