Kamil
Kamil

Reputation: 131

SEO friendly routing of Angular app on Cloudfront

I have SPA application in Angular 7. I also have Java application with REST services, deployed on ElasticBeanstalk (with loadbalancer). I want to use CloudFront and S3 to host frontend part. It was working good with AngularJS, when I was using "old" version of urls (with # sign). Now, when I want to use html5 routing I'm facing multiple issues.

The best solution so far is redirect all 404/403 requests to index.html page. But this is not SEO friendly. I spent couple days on reasearch. And I can't beleieve there is no good solution to solve this. Since SPA are very popular and AWS is very popular what all these people do? It's very common scenario and it's hard to believe that all SPA use redirect to index.html on 404 error.

Upvotes: 0

Views: 960

Answers (1)

Lucas Santos
Lucas Santos

Reputation: 3261

You're right, from an SEO perspective, if the page does not exists, it should return HTTP 404 status code. AWS CloudFront does not know about your front end routes which is handled by angular router.

You can solve that using some options:

  • AWS Lambda: You can write a custom aws lambda function which will check all incoming request and will change response status code (404) if the URL does not exist. But aws lambda needs to know what are the routes of your website (e.g you can create a json file with all the routes and upload it to the lambda function at build/deploy time, etc). I've used this function and it worked like a charm, but it sounds to be a complex job to do a simple task. You need to read and understand Lambda@Edge events to know how to use each of them. Lambda functions are really powerful, but in my experience, they are not really fast to be deployed and applied to all distribution edges every time.

  • AWS Amplify: AWS has created this new service to host single page applications. (has a lot of facilities compared to CloudFront - and also uses cloudfront) In AWS Amplify you can set redirect rules and change responses status code. You could create a script which read all routes from your front end application and set all redirects to 404 routes on aws amplify at build/deploy time. (You can search if already exists any lib to help on that).

  • You might find some libraries to help you with reading all routes from your website and sending that to your cloud provider. Some cloud services as netlify already handle that for you. For example, if you deploy a gatsby react site to netlify, they will read all of our front end routes and will return HTTP status code 404 if your page does not exists.

  • The challenge is: how can you let your hosting service (aws cloudfront, amplify) know all existent routes from your front end application and based on that, return 404 if the page does not exist, avoiding always returning 200.

Hope it helps, please keep us updated if you find any other possible solutions.

Upvotes: 1

Related Questions