Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I serve a React application from an Spring Boot application?

I would like to serve the results of the Webpack build of a ReactJS UI application from a Spring Boot server application.

As the Webpack build generates all the assets in a "dist" folder i.e. index.html, bundle.js, etc... Accessed as i.e. http://localhost/index.html

And the Spring Boot application serves the API URLs from i.e. http://localhost/api/xxx

like image 863
jordiburgos Avatar asked Dec 17 '22 16:12

jordiburgos


1 Answers

  1. create .env file in the root of react project (next to package.json)
  2. put PUBLIC_URL=/nameContextRoot in .env file (name of context root typically is name of war file)
  3. build react project npm run build

For me it generates its contents in build directory of react project

  1. copy the contents of the build directory to the spring-boot apps static directory

static directory should be a normal folder in src/main/resources

  1. clean and rebuild spring boot project and run it

  2. Contents are now properly served

UPDATE

Spring Boot structure

D:.
├───.mvn
│   └───wrapper
├───.settings
├───src
│   ├───main
│   │   ├───java
│   │   │   └───my.java.stuff
│   │   ├───resources
│   │   │   └───static
│   │   │       └───static
│   │   │           ├───css
│   │   │           └───js
│   │   └───webapp
│   └───test
│       └───java
│           └───my.java.tests
├───target
│   ├───classes
│   │   ├───java.classes
│   │   └───static
│   │       ├───css
│   │       ├───js
│   │       └───static
│   │           ├───css
│   │           └───js
│   ├───generated-sources
│   │   └───annotations
│   ├───m2e-wtp
│   │   └───web-resources
│   │       └───META-INF
│   │           └───maven
│   │               └───java.stuff
│   ├───maven-archiver
│   ├───maven-status
│   │   └───maven-compiler-plugin
│   │       └───compile
│   │           └───default-compile
│   ├───rclient-0.0.1-SNAPSHOT
│   │   ├───META-INF
│   │   └───WEB-INF
│   │       ├───classes
│   │       │   ├───java stuff
│   │       │   └───static
│   │       └───lib
│   └───test-classes
└───WebContent
    └───META-INF

ReactJS project structure

D:.
├───build
│   └───static
│       ├───css
│       └───js
├───node_modules
├───public
└───src
    ├───components
    ├───domain
    └───util

Your api endpoints will be also served below the context root. They have nothing to do with React.

The hint of @Codo to use a reverse proxy to access the static content is still valid. But here you asked specifically for how to host the react app in a spring boot application.

like image 164
arnonuem Avatar answered Dec 31 '22 02:12

arnonuem