[SOLVED] Create a 404.json?

I am not sure how to tell hugo I need my 404 as a json.

Usually I uselayouts/404.html but with layouts/404.json, the page is not built.

I have tried adding to to layouts/_default/404.json but nope.

Should I add the page to the config outputs array, and if so how ? This below does not work:

[outputs]
  404 = ["json"]

I may be able to help you if you can explain … why you need this?

1 Like

Sure, I’m playing around to build a small RESTful get API with Hugo. Had fun so far, just want a proper json response along with error code to return when no content is found.

You can just make whatever you want as 404.json and then set that as the thing your API errors to. I mean, that is how it works in HTML, we tell the server to serve the 404.html we generated.

Addendum: if for some reason you are including additional info in your 404.json (such as build time or something), you can add it to the home page as a custom output format.

I still don’t understand … But never mind:

[outputs]
  404 = ["json"]

Needs to be:

[outputs]
  "404" = ["json"]

… but that will, by default, give you index.json.

So you may have to create an output format definition for your 404. Or you could just dump your 404.json file into your home bundle.

Note that the 404.html generated by Hugo follows some old pre-output-format code path.

Doesn’t seem to work, that may be because my homepage already is set for that index.json

Or I’ll just drop it in static/ but I was hoping for something more sophisticated than that in case I need different error code by sections or something.

Thanks I’ll look into it.

No, that’s not it. I remember now. The “404” Kind is kind of special.

So what you need to do is this:

  1. Create a new output format, say "404"
    2… Then use that:
[outputs]
  "home" = ["json", "404"]
2 Likes

Yep! Works like a charm.

Tanks a lot!