July 05, 2019

How to host React JS code with Spring Boot Application

Sometimes we got a requirement where we need to configure react application so that it can be serve in Spring Boot Application. Means, both Spring boot application and react js code can be served from same server.

Following are the steps we need to follow to make it happen:
  1. Put all of your html, js, css, etc. files to src/main/resources/static. Under resources folder create a static folder and under it paste all your frontend code. 
  2. Add one ResourceResolver Class to Spring as below:

    
    @Configuration
    public class Config implements WebMvcConfigurerAdapter {
    
        @Override
        public void addResourceHandlers(ResourceHandlerRegistry registry) {
            ResourceResolver resolver = new ReactResourceResolver();
            registry.addResourceHandler("/**")
                    .resourceChain(true)
                    .addResolver(resolver);
        }
    
        public class ReactResourceResolver implements ResourceResolver {
            // root dir of react files
            private static final String REACT_DIR = "/static/";
            private static final String REACT_STATIC_DIR = "static";
            private Resource index = new ClassPathResource(REACT_DIR + "index.html");
            private List rootStaticFiles = Arrays.asList("favicon.io",
                    "asset-manifest.json", "manifest.json", "service-worker.js");
    
            @Override
            public Resource resolveResource(
                HttpServletRequest request, String requestPath,
                List locations, ResourceResolverChain chain) {
                return resolve(requestPath, locations);
            }
    
            @Override
            public String resolveUrlPath(
                String resourcePath, List locations,
                ResourceResolverChain chain) {
                Resource resolvedResource = resolve(resourcePath, locations);
                if (resolvedResource == null) {
                    return null;
                }
                try {
                    return resolvedResource.getURL().toString();
                } catch (IOException e) {
                    return resolvedResource.getFilename();
                }
            }
    
            private Resource resolve(
                String requestPath, List locations) {
    
                if (requestPath == null) return null;
    
                if (rootStaticFiles.contains(requestPath)
                        || requestPath.startsWith(REACT_STATIC_DIR)) {
                    return new ClassPathResource(REACT_DIR + requestPath);
                } else
                    return index;
            }
    
        }
    }
    
    
Its done. Application frontend will run as smooth.

No comments:

Post a Comment