Ryan Ryan - 1 year ago 98
AngularJS Question

AngularJS and Handling 404 Errors

What is the best way to serve up proper 404's with an AngularJS app?

A little background: I'm building an Angular app and have opted to use


because I want the URLs to appear natural (and indistinguishable from a multi-page "traditional" web app).

On the server side (a simple Python Flask app), I have a catch-all handler that redirects everything to the angular app:

@app.route('/', defaults={'path': ''})
def index(path):
return make_response(open('Ang/templates/index.html').read())

Now, I'm trying to figure out what to do with 404 errors. Most of the Angular apps I've seen do the following:

.otherwise({ redirectTo: '/' })

which means that there is no way they can serve up a proper 404.

However, I would much rather return a proper 404, with a 404 status code (mainly for SEO purposes).

What is the best way to handle 404s with Angular? Should I not worry about it and stick with a catch-all? Or should I remove the catch-all and serve up proper 404's on the server side?

edited for clarity

Answer Source

After playing around for a bit, as well as some discussions with Miguel, I compiled a few different solutions:

  1. Just use a catch-all and don't worry about proper 404's. This can be set up with server-side code (like in my original solution), or better, with URL re-writing on your web server.
  2. Reserve a certain section of your site for your angular app (like /app). For this section, set up a catch-all and don't worry about proper 404's. Your other pages will be served up as regular pages and visiting any invalid URL that doesn't start with /app will result in a proper 404.
  3. Continuously make sure that all of your routes in app.js are mirrored in your server-side code (yes, pretty annoying), where you'll have those routes serve up your angular app. All other routes will 404.

P.S. The second option is my personal favorite. I've tried this out and it works quite well.