DEV Community


How to run SPA webapp on Spring Boot 2.x

Ukjin Yang
I'm a freelance full stack developer, from hell.
Updated on ・1 min read

TL;DR scroll down, get the sources below and taste it.

Most common web server with SPA flavor, All routes will forward to /index.html.
Yes. Spring boot also can do this. but it's pretty hard to figure it out until now. let's do this.

How much difficult to resolve this?
touch NO.
write @Configuration? NOPE.
write @ControllerAdvice? NAH.
Why don't think easy peasy lemon squeezy?

just write a class with @Controller and implements ErrorController interface.
that's all. here's the code!

import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class SpaErrorController implements ErrorController {

    public Object error(HttpServletRequest request, HttpServletResponse response) {
        // place your additional code here (such as error logging...)
        if (request.getMethod().equalsIgnoreCase( {
            response.setStatus(HttpStatus.OK.value()); // optional.
            return "forward:/index.html"; // forward to static SPA html resource.
        } else {
            return ResponseEntity.notFound().build(); // or your REST 404 blabla...

    public String getErrorPath() {
        return "/error";
Enter fullscreen mode Exit fullscreen mode

Don't think other things, just compile and run.
You'll never see whitelabel error page and ALL routes will foward to index.html.
it's SPA style.

I'm using this solution in real world. ye... uhmm.. pretty good.

But remember, splitting front-end and back-end will be better choice; because of REUSABLE, comfortable deploying, other good point that you know.

Discussion (1)

bravemaster619 profile image

LOL, never thought this way. What a hack!