Node.js + Prepr CMS

This is the official Node.js + Prepr guide. It’ll explain to you how to quickly set up a Prepr client in your Node application and use it to fetch data from the Prepr CMS.

Getting started

In this guide, you’ll follow an example that’ll teach you how to set up a minimalistic Node application making use of Express (a Node framework), set up a Prepr client and serve the data received using it to the client through a get request.

Prerequisites

This guide assumes that you’ve:

  • An active Prepr account.
  • Set-up an environment on Prepr CMS, preferably using the demo data provided by Prepr. This can be done by clicking on Load demo data when setting up the environment.

Setting up a Node application

To begin, create a directory for your application and enter it using the following commands:

mkdir prepr-node
cd prepr-node

Initialize your project using npm init -y.

Install necessary packages:

npm install express nodemon dotenv

Update your package.json file to have app.js as your main entry point and include the following watch script under scripts:

"watch": "nodemon app",

Now, create a file named app.js using touch app.js and add the following code into it:

const express = require("express");
const app = express();
const port = process.env.PORT || 3000;
 
app.get("/", (req, res) => {
 res.send("Hello world");
});
 
app.listen(port, () => {
 console.log(`App listening on port: ${port}`);
});

Run the application using following command:

npm run watch

Now, upon visiting http://localhost:3000/, you should see the following output:

Localhost:3000

Creating a Prepr client

Close the server you started in the above step and add the Prepr’s Javascript SDK to your app by using the following command:

npm install @preprio/nodejs-sdk 

Create a services directory in the root of your project and in here, create a file named prepr.js using the following commands:

mkdir services
cd services
touch prepr.js

You’ll use this file to create and configure your Prepr client with the help of createPreprClient provided by the SDK. The client will be used to make API requests to endpoints provided by the Prepr CMS in your Node application.

Add the following code to this file:

require("dotenv").config();
const { createPreprClient } = require("@preprio/nodejs-sdk");
 
const prepr = createPreprClient({
  token: process.env.PREPR_ACCESS_TOKEN, // You can find one in your Prepr environment
  baseUrl: "https://graphql.prepr.io/graphql",
  userId: null, // Optional, used for AB testing implmentations
});
 
module.exports = { prepr };

Prepr recommends using environment variables to store your sensitive information like access token. To add environment variables, create a .env file in the root directory of your project and add the variable like this:

PREPR_ACCESS_TOKEN=<your access token>

Writing GraphQL query

Now, let’s write the GraphQL query that you’ll use in this example.

Create a queries directory in the root of your project and in here, create a file named preprQueries.js using the following commands from the root of your project:

mkdir queries
cd queries
touch preprQueries.js

Add the following code to this file:

const GetPosts = `
query GetPostsQuery {
  posts: Posts {
    items {
      _id
      _slug
      title
    }
  }
}`;
 
module.exports = { GetPosts };

If you’re using the same preloaded demo data in your CMS environment as mentioned above in the Prerequisites section, you should have 5 posts in there. This query, GetPosts, will be used to fetch the post titles.

In case, you’re not using the demo data provided by Prepr then your query might be different. To test your query, you can make use of Explorer (opens in a new tab) provided under Apollo Studio’s sandbox mode. There you can easily create a query with the help of the documentation pane and check the results in real time. All you’ll need is your unique graphql endpoint, All the necessary information about the endpoint can be found here.

Fetching and sending data as response

Open app.js in the root of your project and replace its content with the following code:

const express = require("express");
const { prepr } = require("./services/prepr");
const { GetPosts } = require("./queries/preprQueries");
 
const app = express();
const port = process.env.PORT || 3000;
 
const posts = [];
 
const preprData = async () => {
 const postsData = await prepr.graphqlQuery(GetPosts).fetch();
 posts.push(...postsData.data.posts.items);
};
 
preprData();
 
// Query for the root path.
app.get("/", (req, res) => {
 res.send({ data: posts });
});
 
// Listen to application port.
app.listen(port, () => {
 console.log(`App listening at http://localhost:${port}`);
});

What you’re doing here is importing the Prepr client and the GraphQL query you created in above sections into your app.js. Then you run the GraphQL query, GetPosts, using the Prepr client and push the data received into the posts array initialized right above it. Finally, you send the posts as response to the get request on the root path of your server.

Run the application again using the watch script.

Now, upon making a get request against your server’s root path or visiting it in the browser, you should see a similar response as shown in the image below:

Localhost result

Learn more

For additional information on using @preprio/nodejs-sdk, checkout its documentation (opens in a new tab).

Was this article helpful?

We’d love to learn from your feedback