Quantcast
Channel: OCPsoft
Viewing all articles
Browse latest Browse all 10

SEO-friendly AngularJS with HTML5 pushState(), Rewrite, and twelve lines of code

$
0
0
ng_logo

While migrating an e-commerce application (piqchocolates.com) from Grails and Tomcat to an AngularJS, Java EE (JAX-RS), and JBoss WildFly stack, I had to make sure that the new platform has feature parity in all areas that are valuable to our business. Search Engine Optimization (SEO) is crucial for us because we primarily market our business on-line. In short, we need search engine optimized URLs, and deep linking; this article will show you how to implement both.

Issues with SEO

My initial research revealed SEO issues with AngularJS fragments and hash bang (“#!”) URLs. Namely, web crawlers don’t know how to follow links properly when applications use this URL scheme.

The work-arounds were cumbersome, so it was time to turn to HTML5 “pushState”, a new browser feature that enables the URL to change without sending full page requests back to the server; “pushState” is painless to enable in an AngularJS application.

Configure the client

var app = angular.module('app', ['ngRoute']);

// Enable html push state
app.config(function($locationProvider) {
  $locationProvider.html5Mode({ enabled: true, requireBase: true });	
});
and
<!doctype html>
<html class="no-js" lang="en">
<head>
    <base href="/"> <!-- this is important -->
</head>
    <body>
    	<script src="libs/angular/angular.js"></script>
    	<script src="scripts/app.js"></script>
    </body>
</html>

The code above ensures that as you navigate your SPA via links and buttons, the browser’s address bar is updated accordingly to represent the new state within the application.

In terms of business value, the more important feature is allowing state to survive through page refreshes. This is where SEO comes into the picture, and with that, Rewrite.

Configure the server

To use Rewrite in a JAX-RS and AngularJS application, simply include this dependency in your project’s `pom.xml` dependencies.

rewrite dependency
<dependency>
   <groupId>org.ocpsoft.rewrite</groupId>
   <artifactId>rewrite-servlet</artifactId>
   <version>2.0.12.Final</version> <!-- or latest version -->
</dependency>

Once you’ve done that. Simply create a Rewrite configuration similar to the following; this redirects all requests (that are not mapped to existing directories or Servlets) to `/index.html`. (This assumes that `/index.html` is the access point to your Angular application.

PushStateConfigurationProvider.javaView the entire file
@RewriteConfiguration
public class PushStateConfigurationProvider extends HttpConfigurationProvider
{
    @Override
    public Configuration getConfiguration(final ServletContext context)
    {
        return ConfigurationBuilder.begin()
            .addRule()
            .when(Direction.isInbound().and(Path.matches("/{path}"))
                .andNot(Resource.exists("/{path}"))
                .andNot(ServletMapping.includes("/{path}")))
            .perform((Log.message(Level.INFO, "Forwarding to index.html from {path}").and(Forward.to("/index.html"))))
            .where("path").matches(".*");
    }

    @Override
    public int priority()
    {
        /* This provides ordering if you have multiple configurations */
        return 10; 
    } 
}

The resulting setup is two lines of code in AngularJS, another ten lines of code for the URL Rewrite Configuration, enables us to have all the configuration in one place, and even includes meaningful and easily configurable logging.

Most importantly, since the site is now web crawler friendly, our application now supports Search Engine Optimization. Additionally, if that’s not all, this configuration is actually incredibly simple, and readable. It should be no trouble to understand what this does when I come back to revisit this code for our next upgrade. Rewrite FTW!

Conclusion

I hope this is helpful to you, and that it reinforces that Java and JavaScript are a combination to be reckoned with.

About Piq Chocolates

Piq Chocolates provides personalized and custom shaped chocolates for gifts, favors, events.

The post SEO-friendly AngularJS with HTML5 pushState(), Rewrite, and twelve lines of code first appeared on OCPsoft.


Viewing all articles
Browse latest Browse all 10

Trending Articles