Set up Prismic

This technology has no Slice Machine integration

This framework has no integration with Prismic's developer tool, Slice Machine. You can still build a Prismic website with this technology by using Prismic's Legacy Builder. However, if you're starting a new project with Prismic, we strongly recommend using a technology that integrates with Slice Machine: Next.js or Nuxt.

This article will teach you how to set up a Prismic repository and connect it to your Express.js project.

Prerequisites

Before you get started, you will need a package manager like npm or Yarn installed globally on your system.

To make sure you have Node installed, run the following in your terminal:

node --version

If you don't have Node or npm, here are some installation guides we recommend:

We also recommend using nodemon for development. You can install it with this command:

npm install nodemon --global

Create a repository in Prismic

First, create a repository in Prismic. Your repository will hold all the content of your project.

Then, add some content to your repo, so that you have something to template in your Express project.

Need some tips on how to get started with your repo? Check out our guides to creating content:

Init Express project

If you don't already have an Express project, run the following commands in your terminal.

Create a directory to hold your application.

Copy
mkdir express-app

Go to your app:

Copy
cd express-app

Init your app as an npm project:

Copy
npm init --yes

Install Express:

Copy
npm install express

Update package.json

To use import syntax, Add "type": "module" to the package.json file.

In scripts, add "start": "node .". This is the script that will be used if you deploy to Heroku.

Install Prismic packages

Run the following command in your terminal to Install and node-fetch Prismic dependencies:

Copy
npm install @prismicio/client node-fetch

Further Learning: What do these dependencies do?

@prismicio/client helps with querying the Prismic API and provides a set of helpers to retrieve the content. node-fetch is used to make network requests to the Prismic Rest API.

Create an API client

The API client provides a collection of methods for querying the Prismic API.

Create a folder called config/. Inside the config/ folder, create a file called prismicConfig.js and paste in the following code:

Copy
// node-fetch is used to make network requests to the Prismic Rest API. 
// In Node.js Prismic projects, you must provide a fetch method to the
// Prismic client.
import fetch from 'node-fetch'
import * as prismic from '@prismicio/client'

const repoName = 'your-repo-name' // Fill in your repository name.
const accessToken = '' // If your repository is private, add an access token.

// The `routes` property is your route resolver. It defines how you will 
// structure URLs in your project. Update the types to match the Custom 
// Types in your project, and edit the paths to match the routing in your 
// project.
const routes = [
  {
    type: 'page',
    path: '/:uid',
  },
]

export const client = prismic.createClient(repoName, { 
  fetch, 
  accessToken,
  routes,
})

The routes option defines the URL structure of your website. Want to know more about how it works? Read link resolver and route resolver.

Connect to the Prismic API

First, create a file called index.js (or whatever you have specified as the main entry point in your package.json).

Copy
touch index.js

Add the following code to the index.js file.

Copy
import path from 'path'
import express from 'express'
import { fileURLToPath } from 'url'
import { client } from './config/prismicConfig.js'

const app = express();
const port = process.env.PORT || 3000

// Set EJS as templating engine
app.set('view engine', 'ejs')
const __dirname = path.dirname(fileURLToPath(import.meta.url))
app.use(express.static(path.join(__dirname, 'views')))

// Add a middleware function that runs on every route. It will inject 
// the prismic context to the locals so that we can access these in 
// our templates.
app.use((req, res, next) => {
  res.locals.ctx = {
    prismic,
  }
  next()
})

// Query for the root path.
app.get('/', async (req, res) => {
  // Here we are retrieving the first document from your API endpoint
  const document = await client.getFirst()
  res.render('page', { document })
})

// Listen to application port.
app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`)
})

Create a view

Once you've retrieved your content and passed it to your view, you can render the content in your template using the helper functions in the @prismicio/client package. We'll learn more about this in Template Content.

We will use EJS templates to render data. Install ejs.

Copy
npm install ejs

Start by creating a folder for our EJS files and then the files themselves.

Copy
mkdir views
touch views/page.ejs

In Express.js, a "view" is the presentation code — the code that renders what users see.

Paste this code into /views/page.ejs:

Copy
<img src="<%- document.data.image.url %>" />
<h1><%- ctx.prismic.asText(document.data.title) %></h1>
<%- ctx.prismic.asHTML(document.data.description) %>

Now, run:

Copy
nodemon

The terminal output should show a server running. When you open it, you should see the start of your site.



Was this article helpful?
Not really
Yes, Thanks

Can't find what you're looking for? Spot an error in the documentation? Get in touch with us on our Community Forum or using the feedback form above.