Issue connecting to preview api

When I try to connect to the preview API using the contentful-management library, I get a 404 when I try to get the environment (master).

Here’s the code:

const contentful = require(“contentful-management”);
const client = contentful.createClient({
host: “preview.contentful.com”,
accessToken: process.env.CONTENTFUL_PREVIEW_TOKEN,
});
const space = await client.getSpace(process.env.CONTENTFUL_SPACE);

// It works OK until this next line where I try to get master. This fails with a 404: The resource could not be found. I also cannot call space.getEnvironments()
const environment = await space.getEnvironment(‘master’);
return environment;

master is our only environment and it is checked by default on the access tokens page:

Any suggestions?

It looks like the problem is that the preview server (https://preview.contentful.com) gives a 404 for /spaces//environments/master. I can successfully get /spaces//environments/master/entries. But the problem is the contentful-management library requires you to get the environment before you can get the entries. So my options seem to be:

  • Use the “plain” version of the API (where you can set a default for the environment)
  • Use a different API
  • Directly make the REST calls

The problem with any of those is that the response is going to look different from the original API response… I was hoping to have the same code process either the published version or the latest (preview) version (i.e., preview it with the same code that displays it)… Any other suggestions?