/dropwizard-react-urlrewrite

Example of URL rewriting in a Dropwizard application with React client using the router's BrowserHistory

Primary LanguageJavaScript

React Browser History Routing with Dropwizard Backend Example

This project is an example of how to use URL rewriting (in a Dropwizard application) to allow for use of React Router's BrowserHistory. The purpose is to allow for using HTML5 URLs (without the #). Though this project uses React, this concept holds true for all client applications that use client side routing, such as Angular.

In this project, we accomplish the URL rewriting with the use of the popular Tucky UrlRewriteFilter. We register the filter with Dropwizard's servlet environment.

@Override
public void run(ExampleConfiguration configuration, Environment environment) throws Exception {
    FilterRegistration.Dynamic registration = environment.servlets()
            .addFilter("UrlRewriteFilter", new UrlRewriteFilter());
    registration.addMappingForUrlPatterns(null, true, "/*");
    registration.setInitParameter("confPath", getConfPath(configuration));
}

The other requirement is to have a configuration file, which we have (src/main/resources/urlrewrite.xml). The file includes only one rule, which will tell the rewriter to forward all requests to matching paths directly to the index.html file.

<urlrewrite>
    <rule>
        <from>^/(?!(api|static/|manifest\.json|assets-manifest\.json|favicon\.ico)).*$</from>
        <to type="forward">/index.html</to>
    </rule>
</urlrewrite>

The client app is built with create-react-app. When you build the client app, you will see all of the artifacts in the build folder of the client-app. If you look at the rewrite configuration, you will see that all those files are listed in the matcher. We are saying that if any request URL does NOT match (negative lookahead), then forward the request. If the URLs do match, then just let the request go on its business as usual.

Install Dependencies and Build

cd client-app && npm i && npm run build && cd ../ && mvn clean package

This will install both the client dependencies and server dependencies and then first build the client project and then the server project. The client distribution files will get copied from the client build dir to the server build dir so that we can just run the server artifact.

Run

java -jar server-app/target/server-app-0.0.1.jar server server-app/example.yml

Endpoints

Base http://localhost:8080

Client

  • /
  • /about
  • /contact
  • /contact/phone
  • /contact/twitter

Server

  • /api/example

If you open a browser and browse to /contact/twitter, you should see the page, which means that the URL rewriting is working. You can check the other URLs also to see that everything's working, even the server API.