How to create 404 page for SSR single blog post?

Probably a super easy question but I can't seem to search and find a solution.

Below is my code for a single post [uid].js inside of /pages/blog directory in my nextjs app.

I recently updated my site to use the @prismicio/client package. When I run this code and go to a post that does not exist I get error - Error: No documents were returned IS there a way I can check for if the query returns nothing?

Previously this logic worked before updating to the new package.

import { client } from "../../prismic-configuration"
import FourOhFour from "../../components/FourOhFour"
import SinglePost from "../../components/SinglePost"

const Post = ({ post, is404 }) => <>{is404 ? <FourOhFour /> : <SinglePost post={post} />}</>

export async function getServerSideProps({ query, res }) {
	console.log(query)
	let post = await client.getByUID("blog_post", query.uid, {
		fetchLinks: [
			"webinar.title",
			...
		],
	})

	console.log(post)

	let is404 = false
	if (post === undefined) {
		is404 = true
		post = {}
	}

	res.setHeader("Cache-Control", "s-maxage=1, stale-while-revalidate")
	return { props: { post, is404 } }
}

export default Post

Thanks!

  • N

Hi @niki.brown,

Thank you for

To investigate further, Could you please tell me how did you initialize the client in prismic-configuration.js? The way to access the client is changed in the new version. Learn more about the latest version in our Client V6 technical reference.

Thanks,
Priyanka

Hi @Priyanka Thanks for the quick reply.

I followed the v6 migration guide so my prismic config looks correct (and my blog post listing page works as well as single blog posts that exist).

import * as prismic from "@prismicio/client"

// -- Prismic API endpoint
const endpoint = prismic.getEndpoint("dronedeploy-www")

// -- Link resolution rules
// Manages links to internal Prismic documents
// Modify as your project grows to handle any new routes you've made
export const linkResolver = (doc) => {
	if (doc.type === "blog_post") {
		return `/blog/${doc.uid}`
	} else if (doc.type === "webinar") {
		// url to dd site since this is still in metalsmith
		return `https://www.dronedeploy.com/resources/webinars/${doc.uid}`
	} else if (doc.type === "story") {
		return `https://www.dronedeploy.com/resources/stories/${doc.uid}`
	} else if (doc.type === "ebook") {
		return `https://www.dronedeploy.com/resources/ebooks/${doc.uid}`
	}
	return "/"
}

// -- Client method to query Prismic
// Connects to the given repository to facilitate data queries
export const client = prismic.createClient(endpoint, { fetch })

@Priyanka Any update on this? Any help is much appreciated.

Thanks!

  • N

Hello @niki.brown

Here are the steps you can do for having a custom 404 page:

  1. Create a 404 page, which you already have done.
  2. Use this 404 with checking response code in your post.js like
const errorCode = res.ok ? false : res.statusCode
if (errorCode) {
    return <FourOhFour/>
  }

Reference: Advanced Features: Custom Error Page | Next.js

Thanks,
Priyanka

@Priyanka Thanks for the update. Still running into issues. Any help would be appreciated as I'm quite confused.

So this makes all my blog posts that exist 404. When I type in a URL that does not exist I'm still getting the same Error: No Documents were returned error:

 1 of 1 unhandled error
Server Error
Error: No documents were returned

This error happened while generating the page. Any console logs will be displayed in the terminal window.
Source
pages/blog/[uid].js (6:12) @ async getServerSideProps

  4 | 
  5 | export async function getServerSideProps({ query, res }) {
> 6 | 	let post = await client.getByUID("blog_post", query.uid, {
    | 	          ^
  7 | 		fetchLinks: [
  8 | 			"webinar.title",
  9 | 			"webinar.uid",

My Updated [uid].js with the error logic as you suggested:

import { client } from "../../prismic-configuration"
import FourOhFour from "../../components/FourOhFour"
import SinglePost from "../../components/SinglePost"

export async function getServerSideProps({ query, res }) {
	let post = await client.getByUID("blog_post", query.uid, {
		fetchLinks: [
			"webinar.title",
			"webinar.uid",
			"webinar.thumbnail",
			"ebook.title",
			"ebook.uid",
			"ebook.thumbnail",
			"story.title",
			"story.uid",
			"story.thumbnail",
		],
	})

	const errorCode = res.ok ? false : res.statusCode

	console.log(res)

	return { props: { post, errorCode } }
}

const Post = ({ post, errorCode }) => {
	if (errorCode) {
		return <FourOhFour />
	}

	return <SinglePost post={post} />
}

export default Post

When I console.log res it appears that res.ok does not exist. This is what res console logs:

<ref *2> ServerResponse {
  _events: [Object: null prototype] { finish: [Function: bound resOnFinish] },
  _eventsCount: 1,
  _maxListeners: undefined,
  outputData: [],
  outputSize: 0,
  writable: true,
  destroyed: false,
  _last: false,
  chunkedEncoding: false,
  shouldKeepAlive: true,
  maxRequestsOnConnectionReached: false,
  _defaultKeepAlive: true,
  useChunkedEncodingByDefault: true,
  sendDate: true,
  _removedConnection: false,
  _removedContLen: false,
  _removedTE: false,
  _contentLength: null,
  _hasBody: true,
  _trailer: '',
  finished: false,
  _headerSent: false,
  _closed: false,
  socket: <ref *1> Socket {
    connecting: false,
    _hadError: false,
    _parent: null,
    _host: null,
    _readableState: ReadableState {
      objectMode: false,
      highWaterMark: 16384,
      buffer: BufferList { head: null, tail: null, length: 0 },
      length: 0,
      pipes: [],
      flowing: true,
      ended: false,
      endEmitted: false,
      reading: true,
      constructed: true,
      sync: false,
      needReadable: true,
      emittedReadable: false,
      readableListening: false,
      resumeScheduled: false,
      errorEmitted: false,
      emitClose: false,
      autoDestroy: true,
      destroyed: false,
      errored: null,
      closed: false,
      closeEmitted: false,
      defaultEncoding: 'utf8',
      awaitDrainWriters: null,
      multiAwaitDrain: false,
      readingMore: false,
      dataEmitted: false,
      decoder: null,
      encoding: null,
      [Symbol(kPaused)]: false
    },
    _events: [Object: null prototype] {
      end: [Array],
      timeout: [Function: socketOnTimeout],
      data: [Function: bound socketOnData],
      error: [Function: socketOnError],
      close: [Array],
      drain: [Function: bound socketOnDrain],
      resume: [Function: onSocketResume],
      pause: [Function: onSocketPause]
    },
    _eventsCount: 8,
    _maxListeners: undefined,
    _writableState: WritableState {
      objectMode: false,
      highWaterMark: 16384,
      finalCalled: false,
      needDrain: false,
      ending: false,
      ended: false,
      finished: false,
      destroyed: false,
      decodeStrings: false,
      defaultEncoding: 'utf8',
      length: 0,
      writing: false,
      corked: 0,
      sync: false,
      bufferProcessing: false,
      onwrite: [Function: bound onwrite],
      writecb: null,
      writelen: 0,
      afterWriteTickInfo: null,
      buffered: [],
      bufferedIndex: 0,
      allBuffers: true,
      allNoop: true,
      pendingcb: 0,
      constructed: true,
      prefinished: false,
      errorEmitted: false,
      emitClose: false,
      autoDestroy: true,
      errored: null,
      closed: false,
      closeEmitted: false,
      [Symbol(kOnFinished)]: []
    },
    allowHalfOpen: true,
    _sockname: null,
    _pendingData: null,
    _pendingEncoding: '',
    server: Server {
      maxHeaderSize: undefined,
      insecureHTTPParser: undefined,
      _events: [Object: null prototype],
      _eventsCount: 5,
      _maxListeners: undefined,
      _connections: 3,
      _handle: [TCP],
      _usingWorkers: false,
      _workers: [],
      _unref: false,
      allowHalfOpen: true,
      pauseOnConnect: false,
      httpAllowHalfOpen: false,
      timeout: 0,
      keepAliveTimeout: 5000,
      maxHeadersCount: null,
      maxRequestsPerSocket: 0,
      headersTimeout: 60000,
      requestTimeout: 0,
      _connectionKey: '6::::3000',
      [Symbol(IncomingMessage)]: [Function: IncomingMessage],
      [Symbol(ServerResponse)]: [Function: ServerResponse],
      [Symbol(kCapture)]: false,
      [Symbol(async_id_symbol)]: 9
    },
    _server: Server {
      maxHeaderSize: undefined,
      insecureHTTPParser: undefined,
      _events: [Object: null prototype],
      _eventsCount: 5,
      _maxListeners: undefined,
      _connections: 3,
      _handle: [TCP],
      _usingWorkers: false,
      _workers: [],
      _unref: false,
      allowHalfOpen: true,
      pauseOnConnect: false,
      httpAllowHalfOpen: false,
      timeout: 0,
      keepAliveTimeout: 5000,
      maxHeadersCount: null,
      maxRequestsPerSocket: 0,
      headersTimeout: 60000,
      requestTimeout: 0,
      _connectionKey: '6::::3000',
      [Symbol(IncomingMessage)]: [Function: IncomingMessage],
      [Symbol(ServerResponse)]: [Function: ServerResponse],
      [Symbol(kCapture)]: false,
      [Symbol(async_id_symbol)]: 9
    },
    parser: HTTPParser {
      '0': [Function: bound setRequestTimeout],
      '1': [Function: parserOnHeaders],
      '2': [Function: parserOnHeadersComplete],
      '3': [Function: parserOnBody],
      '4': [Function: parserOnMessageComplete],
      '5': [Function: bound onParserExecute],
      '6': [Function: bound onParserTimeout],
      _headers: [],
      _url: '',
      socket: [Circular *1],
      incoming: [IncomingMessage],
      outgoing: null,
      maxHeaderPairs: 2000,
      _consumed: true,
      onIncoming: [Function: bound parserOnIncoming],
      [Symbol(owner_symbol)]: [HTTPServerAsyncResource]
    },
    on: [Function: socketListenerWrap],
    addListener: [Function: socketListenerWrap],
    prependListener: [Function: socketListenerWrap],
    setEncoding: [Function: socketSetEncoding],
    _paused: false,
    _httpMessage: [Circular *2],
    timeout: 0,
    [Symbol(async_id_symbol)]: 20533,
    [Symbol(kHandle)]: TCP {
      reading: true,
      onconnection: null,
      _consumed: true,
      [Symbol(owner_symbol)]: [Circular *1]
    },
    [Symbol(kSetNoDelay)]: false,
    [Symbol(lastWriteQueueSize)]: 0,
    [Symbol(timeout)]: Timeout {
      _idleTimeout: -1,
      _idlePrev: null,
      _idleNext: null,
      _idleStart: 86495,
      _onTimeout: null,
      _timerArgs: undefined,
      _repeat: null,
      _destroyed: true,
      [Symbol(refed)]: false,
      [Symbol(kHasPrimitive)]: false,
      [Symbol(asyncId)]: 20666,
      [Symbol(triggerId)]: 20662
    },
    [Symbol(kBuffer)]: null,
    [Symbol(kBufferCb)]: null,
    [Symbol(kBufferGen)]: null,
    [Symbol(kCapture)]: false,
    [Symbol(kBytesRead)]: 0,
    [Symbol(kBytesWritten)]: 0,
    [Symbol(RequestTimeout)]: undefined
  },
  _header: null,
  _keepAliveTimeout: 5000,
  _onPendingData: [Function: bound updateOutgoingData],
  req: IncomingMessage {
    _readableState: ReadableState {
      objectMode: false,
      highWaterMark: 16384,
      buffer: BufferList { head: null, tail: null, length: 0 },
      length: 0,
      pipes: [],
      flowing: null,
      ended: true,
      endEmitted: false,
      reading: false,
      constructed: true,
      sync: true,
      needReadable: false,
      emittedReadable: false,
      readableListening: false,
      resumeScheduled: false,
      errorEmitted: false,
      emitClose: true,
      autoDestroy: true,
      destroyed: false,
      errored: null,
      closed: false,
      closeEmitted: false,
      defaultEncoding: 'utf8',
      awaitDrainWriters: null,
      multiAwaitDrain: false,
      readingMore: true,
      dataEmitted: false,
      decoder: null,
      encoding: null,
      [Symbol(kPaused)]: null
    },
    _events: [Object: null prototype] { end: [Function: clearRequestTimeout] },
    _eventsCount: 1,
    _maxListeners: undefined,
    socket: <ref *1> Socket {
      connecting: false,
      _hadError: false,
      _parent: null,
      _host: null,
      _readableState: [ReadableState],
      _events: [Object: null prototype],
      _eventsCount: 8,
      _maxListeners: undefined,
      _writableState: [WritableState],
      allowHalfOpen: true,
      _sockname: null,
      _pendingData: null,
      _pendingEncoding: '',
      server: [Server],
      _server: [Server],
      parser: [HTTPParser],
      on: [Function: socketListenerWrap],
      addListener: [Function: socketListenerWrap],
      prependListener: [Function: socketListenerWrap],
      setEncoding: [Function: socketSetEncoding],
      _paused: false,
      _httpMessage: [Circular *2],
      timeout: 0,
      [Symbol(async_id_symbol)]: 20533,
      [Symbol(kHandle)]: [TCP],
      [Symbol(kSetNoDelay)]: false,
      [Symbol(lastWriteQueueSize)]: 0,
      [Symbol(timeout)]: Timeout {
        _idleTimeout: -1,
        _idlePrev: null,
        _idleNext: null,
        _idleStart: 86495,
        _onTimeout: null,
        _timerArgs: undefined,
        _repeat: null,
        _destroyed: true,
        [Symbol(refed)]: false,
        [Symbol(kHasPrimitive)]: false,
        [Symbol(asyncId)]: 20666,
        [Symbol(triggerId)]: 20662
      },
      [Symbol(kBuffer)]: null,
      [Symbol(kBufferCb)]: null,
      [Symbol(kBufferGen)]: null,
      [Symbol(kCapture)]: false,
      [Symbol(kBytesRead)]: 0,
      [Symbol(kBytesWritten)]: 0,
      [Symbol(RequestTimeout)]: undefined
    },
    httpVersionMajor: 1,
    httpVersionMinor: 1,
    httpVersion: '1.1',
    complete: true,
    rawHeaders: [
      'Host',
      'localhost:3000',
      'Connection',
      'keep-alive',
      'Cache-Control',
      'max-age=0',
      'sec-ch-ua',
      '" Not A;Brand";v="99", "Chromium";v="98", "Google Chrome";v="98"',
      'sec-ch-ua-mobile',
      '?0',
      'sec-ch-ua-platform',
      '"macOS"',
      'Upgrade-Insecure-Requests',
      '1',
      'User-Agent',
      'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.80 Safari/537.36',
      'Accept',
      'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
      'Sec-Fetch-Site',
      'same-origin',
      'Sec-Fetch-Mode',
      'navigate',
      'Sec-Fetch-Dest',
      'document',
      'Referer',
      'http://localhost:3000/blog/how-ground-robotics-validate-subcontractors',
      'Accept-Encoding',
      'gzip, deflate, br',
      'Accept-Language',
      'en-US,en;q=0.9,es;q=0.8',
      'Cookie',
      '_ga=GA1.1.1199398227.1590535170; _mkto_trk=id:330-JZX-744&token:_mch-localhost-1590535169823-20549; __adroll_fpc=69472a91eb8a59a734d59f58366f07ad-1590535170394; optimizelyEndUserId=oeu1595446266323r0.6114480482785638; _uetvid=b23601004eca11eb842ceb36aa17e5d0; _gd_visitor=6cf2d54f-9924-4792-8abf-d793465e4a35; drift_aid=14516278-7ce1-4b5a-950c-a95b61621de5; driftt_aid=14516278-7ce1-4b5a-950c-a95b61621de5; fpestid=j0LPWQB56Hr8O2cYJGPS5ZGgiCTPsM5Mrx89oEXGe2FUsdcks-oaUQX-XEM4XkgaQtWOpw; OptanonAlertBoxClosed=2021-09-29T00:23:59.463Z; adminer_export=output%3Dgz%26format%3Dsql%26db_style%3D%26routines%3D1%26events%3D1%26table_style%3DDROP%252BCREATE%26auto_increment%3D%26triggers%3D1%26data_style%3DINSERT; adminer_permanent=c2VydmVy--cm9vdA%3D%3D-bG9jYWw%3D%3A638EaMaqhVA%3D; trans_flag=true; _gcl_au=1.1.2080277190.1644356610; utm_medium=; utm_source=; utm_term=; utm_campaign=; utm_content=; origin_referrer=; _clck=10cjipy|1|eyt|0; _an_uid=0; mp_a84e7a6dd3cfcd0c8a5d3fa1a6cb6eaa_mixpanel=%7B%22distinct_id%22%3A%20%22179ee288993807-0511cefe0bdd0a-1f3b6255-2a3000-179ee288994b06%22%2C%22%24device_id%22%3A%20%22179ee288993807-0511cefe0bdd0a-1f3b6255-2a3000-179ee288994b06%22%2C%22%24initial_referrer%22%3A%20%22http%3A%2F%2Flocalhost%3A3000%2Fsolutions%2Fget-a-demo%2F%3Fedit%22%2C%22%24initial_referring_domain%22%3A%20%22localhost%3A3000%22%7D; mp_817d4fa5367887b531743e9bf1ac006e_mixpanel=%7B%22distinct_id%22%3A%20%2217a2207cd6884e-05ac90b3eba75a-34647300-1aeaa0-17a2207cd6915c%22%2C%22%24device_id%22%3A%20%2217a2207cd6884e-05ac90b3eba75a-34647300-1aeaa0-17a2207cd6915c%22%2C%22%24initial_referrer%22%3A%20%22http%3A%2F%2Flocalhost%3A3000%2Fproduct%2Fsecurity%2F%22%2C%22%24initial_referring_domain%22%3A%20%22localhost%3A3000%22%7D; OptanonConsent=isGpcEnabled=0&datestamp=Tue+Feb+08+2022+15%3A08%3A08+GMT-0800+(Pacific+Standard+Time)&version=6.30.0&isIABGlobal=false&hosts=&landingPath=NotLandingPage&groups=C0001%3A1%2CC0002%3A0%2CC0003%3A0%2CC0004%3A0%2CC0005%3A0&geolocation=US%3BCA&AwaitingReconsent=false; __ar_v4=PZ3J2DB42BCOPNJYNZPCZK%3A20220109%3A95%7CGPKY6TDDQNDEXLIHZLCKUU%3A20220109%3A95%7CBZMLPPJ4FFGGJAGNYMS7QK%3A20220109%3A95'
    ],
    rawTrailers: [],
    aborted: false,
    upgrade: false,
    url: '/blog/how-ground-robotics-validate-subcontractors',
    method: 'GET',
    statusCode: null,
    statusMessage: null,
    client: <ref *1> Socket {
      connecting: false,
      _hadError: false,
      _parent: null,
      _host: null,
      _readableState: [ReadableState],
      _events: [Object: null prototype],
      _eventsCount: 8,
      _maxListeners: undefined,
      _writableState: [WritableState],
      allowHalfOpen: true,
      _sockname: null,
      _pendingData: null,
      _pendingEncoding: '',
      server: [Server],
      _server: [Server],
      parser: [HTTPParser],
      on: [Function: socketListenerWrap],
      addListener: [Function: socketListenerWrap],
      prependListener: [Function: socketListenerWrap],
      setEncoding: [Function: socketSetEncoding],
      _paused: false,
      _httpMessage: [Circular *2],
      timeout: 0,
      [Symbol(async_id_symbol)]: 20533,
      [Symbol(kHandle)]: [TCP],
      [Symbol(kSetNoDelay)]: false,
      [Symbol(lastWriteQueueSize)]: 0,
      [Symbol(timeout)]: Timeout {
        _idleTimeout: -1,
        _idlePrev: null,
        _idleNext: null,
        _idleStart: 86495,
        _onTimeout: null,
        _timerArgs: undefined,
        _repeat: null,
        _destroyed: true,
        [Symbol(refed)]: false,
        [Symbol(kHasPrimitive)]: false,
        [Symbol(asyncId)]: 20666,
        [Symbol(triggerId)]: 20662
      },
      [Symbol(kBuffer)]: null,
      [Symbol(kBufferCb)]: null,
      [Symbol(kBufferGen)]: null,
      [Symbol(kCapture)]: false,
      [Symbol(kBytesRead)]: 0,
      [Symbol(kBytesWritten)]: 0,
      [Symbol(RequestTimeout)]: undefined
    },
    _consuming: false,
    _dumped: false,
    cookies: [Getter/Setter],
    __NEXT_INIT_URL: '/blog/how-ground-robotics-validate-subcontractors',
    __NEXT_INIT_QUERY: {},
    __nextHadTrailingSlash: undefined,
    [Symbol(kCapture)]: false,
    [Symbol(kHeaders)]: {
      host: 'localhost:3000',
      connection: 'keep-alive',
      'cache-control': 'max-age=0',
      'sec-ch-ua': '" Not A;Brand";v="99", "Chromium";v="98", "Google Chrome";v="98"',
      'sec-ch-ua-mobile': '?0',
      'sec-ch-ua-platform': '"macOS"',
      'upgrade-insecure-requests': '1',
      'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.80 Safari/537.36',
      accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
      'sec-fetch-site': 'same-origin',
      'sec-fetch-mode': 'navigate',
      'sec-fetch-dest': 'document',
      referer: 'http://localhost:3000/blog/how-ground-robotics-validate-subcontractors',
      'accept-encoding': 'gzip, deflate, br',
      'accept-language': 'en-US,en;q=0.9,es;q=0.8',
      cookie: '_ga=GA1.1.1199398227.1590535170; _mkto_trk=id:330-JZX-744&token:_mch-localhost-1590535169823-20549; __adroll_fpc=69472a91eb8a59a734d59f58366f07ad-1590535170394; optimizelyEndUserId=oeu1595446266323r0.6114480482785638; _uetvid=b23601004eca11eb842ceb36aa17e5d0; _gd_visitor=6cf2d54f-9924-4792-8abf-d793465e4a35; drift_aid=14516278-7ce1-4b5a-950c-a95b61621de5; driftt_aid=14516278-7ce1-4b5a-950c-a95b61621de5; fpestid=j0LPWQB56Hr8O2cYJGPS5ZGgiCTPsM5Mrx89oEXGe2FUsdcks-oaUQX-XEM4XkgaQtWOpw; OptanonAlertBoxClosed=2021-09-29T00:23:59.463Z; adminer_export=output%3Dgz%26format%3Dsql%26db_style%3D%26routines%3D1%26events%3D1%26table_style%3DDROP%252BCREATE%26auto_increment%3D%26triggers%3D1%26data_style%3DINSERT; adminer_permanent=c2VydmVy--cm9vdA%3D%3D-bG9jYWw%3D%3A638EaMaqhVA%3D; trans_flag=true; _gcl_au=1.1.2080277190.1644356610; utm_medium=; utm_source=; utm_term=; utm_campaign=; utm_content=; origin_referrer=; _clck=10cjipy|1|eyt|0; _an_uid=0; mp_a84e7a6dd3cfcd0c8a5d3fa1a6cb6eaa_mixpanel=%7B%22distinct_id%22%3A%20%22179ee288993807-0511cefe0bdd0a-1f3b6255-2a3000-179ee288994b06%22%2C%22%24device_id%22%3A%20%22179ee288993807-0511cefe0bdd0a-1f3b6255-2a3000-179ee288994b06%22%2C%22%24initial_referrer%22%3A%20%22http%3A%2F%2Flocalhost%3A3000%2Fsolutions%2Fget-a-demo%2F%3Fedit%22%2C%22%24initial_referring_domain%22%3A%20%22localhost%3A3000%22%7D; mp_817d4fa5367887b531743e9bf1ac006e_mixpanel=%7B%22distinct_id%22%3A%20%2217a2207cd6884e-05ac90b3eba75a-34647300-1aeaa0-17a2207cd6915c%22%2C%22%24device_id%22%3A%20%2217a2207cd6884e-05ac90b3eba75a-34647300-1aeaa0-17a2207cd6915c%22%2C%22%24initial_referrer%22%3A%20%22http%3A%2F%2Flocalhost%3A3000%2Fproduct%2Fsecurity%2F%22%2C%22%24initial_referring_domain%22%3A%20%22localhost%3A3000%22%7D; OptanonConsent=isGpcEnabled=0&datestamp=Tue+Feb+08+2022+15%3A08%3A08+GMT-0800+(Pacific+Standard+Time)&version=6.30.0&isIABGlobal=false&hosts=&landingPath=NotLandingPage&groups=C0001%3A1%2CC0002%3A0%2CC0003%3A0%2CC0004%3A0%2CC0005%3A0&geolocation=US%3BCA&AwaitingReconsent=false; __ar_v4=PZ3J2DB42BCOPNJYNZPCZK%3A20220109%3A95%7CGPKY6TDDQNDEXLIHZLCKUU%3A20220109%3A95%7CBZMLPPJ4FFGGJAGNYMS7QK%3A20220109%3A95'
    },
    [Symbol(kHeadersCount)]: 32,
    [Symbol(kTrailers)]: null,
    [Symbol(kTrailersCount)]: 0,
    [Symbol(RequestTimeout)]: undefined
  },
  _sent100: false,
  _expect_continue: false,
  statusCode: 200,
  flush: [Function: flush],
  write: [Function: write],
  end: [Function: end],
  on: [Function: on],
  writeHead: [Function: writeHead],
  [Symbol(kCapture)]: false,
  [Symbol(kNeedDrain)]: false,
  [Symbol(corked)]: 0,
  [Symbol(kOutHeaders)]: null
}

@Priyanka any update?

Thanks!

@Prismic-Support-Team Any response to this? I've been waiting for a while to get this figured out. This is the last piece to workout before launching my project. Happy to give someone access to our private repo to help troubleshoot.

Thank you!

Hello @niki.brown,

Sorry for being delay in replying to you back. I was out of the office last week.

It would be better to share your Project code (either Zip file or GitHub repo) with me. It helps me debug the code.

Thanks,
Priyanka

@Prismic-Support-Team Here is a zip of my branch https://nikib.ro/wn/screenshots/marketing-site-404-page-troubleshooting.zip_2022-02-15_10-09-05.zip

To reproduce the error after setting things up (npm install) npm run dev Blog is located at http://localhost:3000/blog/ if you visit a post that does not exist: http://localhost:3000/blog/dronedeploys-first-annual-social-impact-reportasdfasdf you get Server Error Error: No documents were returned

Thanks!

  • N

Hello @niki.brown

Prismic client API throws an error if no documents were returned. We need to handle it by exception handling. I am using try…catch statements that handle if any exception is thrown:

import { client } from "../../prismic-configuration"
import FourOhFour from "../../components/FourOhFour"
import SinglePost from "../../components/SinglePost"

export async function getServerSideProps({ query, res }) {
  let post = {}
  var errorCode = ""
  try {
    post = await client.getByUID("blog_post", query.uid, {
     fetchLinks: [
       "webinar.title",
	"webinar.uid",
	"webinar.thumbnail",
	"ebook.title",
	 "ebook.uid",
	 "ebook.thumbnail",
	 "story.title",
	 "story.uid",
	 "story.thumbnail",
     ],
  })
} catch (e) {
    if (!e.response) errorCode = "404"
 }

	// const errorCode = res.ok ? false : res.statusCode

  return { props: { post, errorCode } }
}

const Post = ({ post, errorCode }) => {
  if (errorCode) {
    return <FourOhFour />
  }

  return <SinglePost post={post} />
}

export default Post

Give this a try and let me know if you have any questions.

Thanks,
Priyanka

@Priyanka Thank you. This worked.

@niki.brown I am happy to help. Let us know if you have any other questions.

Hi Priyanka,

It doesn't feel right that a getByUID call with an unexisting uid trigger a 'api_parsing_error' error.
I usually expect a null document or a better error :confused:

ParsingError: [function at(..)] unexpected field 'my.page.uid' on line:1 col:6 in query '[[at(my.page.uid, "guide")]]'
[[at(my.page.uid, "guide")]]
     ^

    at Client.fetch (file:///home/david/Works/OLYBe/website/node_modules/@prismicio/client/dist/index.js:557:15)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at async Client.getFirst (file:///home/david/Works/OLYBe/website/node_modules/@prismicio/client/dist/index.js:282:20)
    at async Client.getByUID (file:///home/david/Works/OLYBe/website/node_modules/@prismicio/client/dist/index.js:318:12)
    at async getStaticProps (/home/david/Works/OLYBe/website/.next/server/pages/[prismicUid].js:204:20)
    at async Object.renderToHTML (/home/david/Works/OLYBe/website/node_modules/next/dist/server/render.js:470:20)
    at async doRender (/home/david/Works/OLYBe/website/node_modules/next/dist/server/base-server.js:878:38)
    at async cacheEntry.responseCache.get.isManualRevalidate.isManualRevalidate (/home/david/Works/OLYBe/website/node_modules/next/dist/server/base-server.js:977:28)
    at async /home/david/Works/OLYBe/website/node_modules/next/dist/server/response-cache.js:72:36 {
  url: '[HIDDEN].prismic.io/api/v2/documents/search?q=%5B%5Bat%28document.type%2C+%22page%22%29%5D%5D&q=%5B%5Bat%28my.page.uid%2C+%22guide%22%29%5D%5D&ref=YlBVHxcAAGfZ1vpZ',
  response: {
    type: 'api_parsing_error',
    message: `[function at(..)] unexpected field 'my.page.uid' on line:1 col:6 in query '[[at(my.page.uid, "guide")]]'\n` +
      '[[at(my.page.uid, "guide")]]\n' +
      '     ^\n',
    pos: { line: 1, column: 6, id: 1, location: 'query' }
  }

Is-it plan to improve things about it? Thanks

Hello @webda2l

Welcome to the Prismic community, and thanks for reaching out to us.

It should indeed return a null or better error. I have passed this on to my dedicated developer. I'll let you know any updates on this.

Thanks,
Priyanka

1 Like