ForbiddenError: Access to this Ref requires an access token

I can't access my custom type data why, I did everything as stated in the Doc.

  • Create an API client

I created the config/ folder with prismicConfig.js

prismicConfig.js

// 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'
import dotEnv from  'dotenv'

dotEnv.config()

const repoName = 'Floema' // Fill in your repository name.
const accessToken = process.env.PRISMIC_ACCESS_TOKEN // 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: 'about',
    path: '/about',
  },
]

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

And connected to the Prismic API in my app.js file

app.js file

import { fileURLToPath } from 'url'
import * as prismicH from '@prismicio/helpers'
import { client } from './config/prismicConfig.js'
import express from 'express'
import dotEnv from  'dotenv'
import path from 'path'

const __filename = fileURLToPath(import.meta.url);


dotEnv.config()

const app = express()
const port = 3000

const __dirname = path.dirname(__filename)

app.set('views', path.join(__dirname, 'views'))
app.set('view engine', 'pug')

app.use((req, res, next) => {
  res.locals.ctx = {
    prismicH,
  }
  next()
})

app.get('/', async (req, res) => {
  
  res.render('pages/home')
  console.log(`dirname is :${__dirname}`)
})

app.get('/about', async (req, res) => {
  
  // Here we are retrieving the first document from your API endpoint
  const document = await client.getFirst('about')
  console.log(document)
  res.render('pages/about', { document })
  
})

app.get('/detail/:id', async (req, res) => {
  res.render('pages/detail')
})

app.get('/collections', async (req, res) => {
  res.render('pages/collections')
})

app.listen(port, () => {
  console.log(`Example app listening on port ${port} and dirname is ${__dirname}`)
})

I set it up only for the about page

this is the error I get in the console

file:///Users/al/Documents/Projects/Floema/floema/node_modules/@prismicio/client/dist/index.js:561
[0] throw new ForbiddenError("error" in json ? json.error : json.message, url, json);
[0] ^
[0]
[0] ForbiddenError: Access to this Ref requires an access token
[0] at Client.fetch (file:///Users/al/Documents/Projects/Floema/floema/node_modules/@prismicio/client/dist/index.js:561:15)
[0] at processTicksAndRejections (node:internal/process/task_queues:96:5)
[0] at async Client.getFirst (file:///Users/al/Documents/Projects/Floema/floema/node_modules/@prismicio/client/dist/index.js:282:20)
[0] at async file:///Users/al/Documents/Projects/Floema/floema/app.js:37:20 {
[0] url: 'https://floema.cdn.prismic.io/api/v2/documents/search?0=a&1=b&2=o&3=u&4=t&ref=YNwauBEAACQAUL2O&routes=[{"type"%3A"about"%2C"path"%3A"%2Fabout"%2C"accessToken*********&access_token=*******,
[0] response: {
[0] type: 'api_security_error',
[0] message: 'Access to this Ref requires an access token',
[0] oauth_initiate: 'https://floema.prismic.io/auth',
[0] oauth_token: 'https://floema.prismic.io/auth/token'
[0] }
[0] }

I provided the access token int config file and it even returns it in the terminal. I'm very confused

Hello @alsalvadorg, I believe res.render is expecting a different parameter. Similar to how is done here:

For example, I'd write the route for /about like this, in this case the Custom Type is called about_post:

app.get('/about', async (req, res) => {
   const aboutpost = await client.getSingle('about_post');
    res.render('about', {
      aboutpost,
   });
})

Same exact mistake

response: {
[0]     type: 'api_security_error',
[0]     message: 'Access to this Ref requires an access token',
[0]     oauth_initiate: 'https://floema.prismic.io/auth',
[0]     oauth_token: 'https://floema.prismic.io/auth/token'
[0]   }
[0] }

How are you passing your private repo's access token?

Yes in the prismicConfig.js file. Just as the guide says. I don’t know if I should pass it elsewhere


// 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'
import dotEnv from  'dotenv'

dotEnv.config()

const repoName = 'Floema' // Fill in your repository name.
const accessToken = process.env.PRISMIC_ACCESS_TOKEN // 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: 'about',
    path: '/about',
  },
]

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

We've opened a feature request to make this error message more descriptive. This happens because we invalidate a master ref after five publications. After that, the master ref becomes unreachable.

For example, if someone on your team publishes a document during a build, it will cause the ref to go out of date.

Can I know what is a ref. Will updating that ref fix my problem? how should I proceed ?.

Yes, the ref is a reference for the version of the content in the API of your repository. Here's the documentation about refs in Prismic:

You're probably storing or caching the ref somewhere in your app.

I have the same error, I had a successful deployment before, but after creating some new slices (nothing fancy) this error started to show up:

[14:12:52.303] Running build in Washington, D.C., USA (East) – iad1 (Hive)
[14:12:52.403] Cloning github.com/agtz92/tpublicitario (Branch: master, Commit: 6b23d36)
[14:12:53.037] Cloning completed: 634.116ms
[14:13:01.251] Restored build cache
[14:13:01.322] Running "vercel build"
[14:13:01.910] Vercel CLI 32.2.4
[14:13:02.241] Detected pnpm-lock.yaml version 6 generated by pnpm 8
[14:13:02.258] Installing dependencies...
[14:13:02.881] Lockfile is up to date, resolution step is skipped
[14:13:02.974] Already up to date
[14:13:03.789]
[14:13:03.803] Done in 1.4s
[14:13:03.822] Detected Next.js version: 13.4.13
[14:13:03.837] Running "pnpm run build"
[14:13:04.335]
[14:13:04.336] > nextjs-starter-prismic-multi-page@0.0.0 build /vercel/path0
[14:13:04.336] > next build
[14:13:04.336]
[14:13:05.172] - info Creating an optimized production build...
[14:13:21.743] - info Compiled successfully
[14:13:21.744] - info Linting and checking validity of types...
[14:13:23.754] - info Collecting page data...
[14:13:24.751] ForbiddenError: Access to this Ref requires an access token
[14:13:24.751] at Client.fetch (/vercel/path0/.next/server/chunks/717.js:2367:27)
[14:13:24.752] at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
[14:13:24.752] at async Client.get (/vercel/path0/.next/server/chunks/717.js:1442:16)
[14:13:24.752] at async Client.dangerouslyGetAll (/vercel/path0/.next/server/chunks/717.js:1507:28)
[14:13:24.752] at async Client.getAllByType (/vercel/path0/.next/server/chunks/717.js:1766:16)
[14:13:24.752] at async Object.generateStaticParams (/vercel/path0/.next/server/app/[uid]/page.js:499:19)
[14:13:24.752] at async buildParams (/vercel/path0/node_modules/.pnpm/next@13.4.13_react-dom@18.2.0_react@18.2.0/node_modules/next/dist/build/utils.js:917:36)
[14:13:24.752] at async /vercel/path0/node_modules/.pnpm/next@13.4.13_react-dom@18.2.0_react@18.2.0/node_modules/next/dist/build/utils.js:934:33
[14:13:24.752] at async /vercel/path0/node_modules/.pnpm/next@13.4.13_react-dom@18.2.0_react@18.2.0/node_modules/next/dist/build/utils.js:1067:117
[14:13:24.752] at async Span.traceAsyncFn (/vercel/path0/node_modules/.pnpm/next@13.4.13_react-dom@18.2.0_react@18.2.0/node_modules/next/dist/trace/trace.js:103:20) {
[14:13:24.752] url: 'https://tpublicitario.cdn.prismic.io/api/v2/documents/search?q=[[at(document.type%2C+"page")]]&pageSize=100&ref=ZPkJhxIAACMAbFbV&routes=[{"type"%3A"page"%2C"path"%3A"%2F%3Auid"}%2C{"type"%3A"page"%2C"uid"%3A"home"%2C"path"%3A"%2F"}%2C{"type"%3A"settings"%2C"path"%3A"%2F"}%2C{"type"%3A"navigation"%2C"path"%3A"%2F"}]',
[14:13:24.753] response: {
[14:13:24.753] type: 'api_security_error',
[14:13:24.753] message: 'Access to this Ref requires an access token',
[14:13:24.753] oauth_initiate: 'https://tpublicitario.prismic.io/auth',
[14:13:24.753] oauth_token: 'https://tpublicitario.prismic.io/auth/token'
[14:13:24.753] }
[14:13:24.753] }
[14:13:24.753]
[14:13:24.753] > Build error occurred
[14:13:24.755] Error: Failed to collect page data for /[uid]
[14:13:24.755] at /vercel/path0/node_modules/.pnpm/next@13.4.13_react-dom@18.2.0_react@18.2.0/node_modules/next/dist/build/utils.js:1156:15
[14:13:24.756] at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
[14:13:24.756] type: 'Error'
[14:13:24.756] }
[14:13:24.815] ELIFECYCLE Command failed with exit code 1.

Hi @alfredo.gtz92,

Can you share the code in your next.js project where you run this query?

My guess is that you need to update your ref, but looking at your code will help me figure out if that's the issue or not.

Yes, I'm also getting errors in the same way. It works when we update the access token. Don't know why its working like this.

I tried changing API access to Open API then Its getting documents from initial master ref and my latest changes are not reflecting. I don’t know how to change the masterRef.

Currently changing the access token on each build thats solving my issue.

@webdev3 When you say you're changing the access token on each build, what do you mean exactly? Can you show me how you're querying your content?

Nothing fancy, everything is default query only

Here is my config

export const createClient = (config) => {
  const client = prismic.createClient(repositoryName, {
    routes,
    accessToken: process.env.PRISMIC_ACCESS_TOKEN,
    fetchOptions:
      process.env.NODE_ENV === "production"
        ? { next: { tags: ["prismic"] }, cache: "force-cache" }
        : { next: { revalidate: 5 } },
    ...config,
  });

  prismicNext.enableAutoPreviews({ client });

  return client;
};

and I'm getting page like this

const page = await client
    .getByUID("product_pages", params.uid)
    .catch(() => notFound());

const page = await client
    .getByUID("industry_pages", params.uid)
    .catch(() => notFound());

const page = await client
    .getByUID("solution_pages", params.uid)
    .catch(() => notFound());

Currently facing the same error with Nextjs in production

My config

export const createClient = (config: prismicNext.CreateClientConfig = {}) => {
	const client = prismic.createClient(repositoryName, {
		routes,
		accessToken: process.env.PRISMIC_ACCESS_TOKEN,
		...config,
		fetchOptions:
			process.env.NODE_ENV === "production"
				? { next: { tags: ["prismic"] }, cache: "force-cache" }
				: { next: { revalidate: 5 } },
		...config,
	});

	prismicNext.enableAutoPreviews({
		client,
		previewData: config.previewData,
		req: config.req,
	});

	return client;
};

Vercel Log error

 response: {
    type: 'api_security_error',
    message: 'Access to this Ref requires an access token',
    oauth_initiate: 'https://***.prismic.io/auth',
    oauth_token: 'https://***.prismic.io/auth/token'
  }
}
[Error: An error occurred in the Server Components render. The specific message is omitted in production builds to avoid leaking sensitive details. A digest property is included on this error instance which may provide additional details about the nature of the error.]

After purging cache in Vercel, everything went back to normal

1 Like

Hey @webdev3 and @michealndo,

We believe that this is an issue with caching in Next.js. We have opened an issue on the Next.js GitHub repository:

Please feel free to upvote and subscribe for updates.

Sam