create spring boot application with next js

·

5 min read

Creating a spring web application is like making a detailed painting, and I prefer to use Next.js for the front part and Spring Boot for the back part. Next.js is great for building the visible parts of the app, and it lets you create the whole application with your special features.

But there are some tricky parts in this journey. Sometimes, you need to make sure that the pictures and other things that don't change stay connected to the back part of the app to give users a smooth experience.

That's where this guide comes in. It's here to teach you how to connect the unchanging parts of your Next.js app with the Spring Boot part. Our main goal is to solve problems like when someone refreshes the webpage or types the web address directly, so everything keeps working well with the Tomcat server, and we use Next.js's features effectively.

If you want to learn how to create a web app with Spring Boot and Next.js, this article will help you navigate through the process.

Create a Nextjs app with the following command

npx create-next-app@latest

This command creates a fresh Next.js project using the latest version, giving you a strong starting point to build the front end of your website.

After you've created the Next.js project, open it in your favorite text editor, like Visual Studio Code. This lets you access and edit the front-end code as needed.

You may need to make some adjustments in the package.json and next.config.js files, and then proceed to build the project.

Fetch Data from the Backend

Create a list.js file in the Next.js project responsible for fetching data from the Spring Boot API. Implement the necessary logic to retrieve data from the backend and render it in the front end.

function List() {
    const [list, setList] = useState([])
    const fetchList = () => {
        fetch("/e3docs/getlist")
            .then(response => {
                return response.json()
            })
            .then(data => {
                setList(data)
            })
    }
    useEffect(() => {
        fetchList()
    }, [])
    function getlist() {
        return list.map((item, i) => {
            return (
                <Fragment key={i}>
                    <tr>
                        <td>
                            {(i + 1)}
                        </td>
                        <td>
                            {item}
                        </td>
                    </tr>
                </Fragment>
            );
        })
    }
    return (
        <main>
            <div style={{ paddingLeft: '34%', paddingTop: '2%', display: 'flex' }}>
                <h2 style={{ paddingRight: '10px' }}>
                    <Link href="/">Home</Link>
                </h2>
                <h2>
                    <Link href="/list">List</Link>
                </h2>
            </div>
            <div style={{ paddingLeft: '34%', paddingTop: '3%' }}>
                <table>
                    <thead>
                        <tr>
                            <th>No.</th>
                            <th>Description</th>
                        </tr>
                    </thead>
                    <tbody>
                        {list.length > 0 && (getlist())}
                    </tbody>
                </table >
            </div>
        </main>
    );
}
export default List;

Create a New Page to Handle Web App Refresh and Direct URL Entry

To handle scenarios like web app refresh or direct URL entry, create a new page in the Next.js project. This page will help to handle the 404 error page in Next JS when the user enters a direct URL into the browser or the page refreshes.

function PageRefresh() {
    const router = useRouter();
    useEffect(() => {
        if (router.isReady) {
            router.push(router.asPath).catch((e) => {
                router.push('/_error');
            });
        }
    }, [router.isReady])
    return (
        <div>Loading...</div>
    );
}
export default PageRefresh;

Build and export a Next.js project that will create an “out” folder with the compiled and optimized Next.js application.

Create a New Project with Spring Initializr

Use Spring Initializr to create a new Spring Boot project. Specify the necessary dependencies and project settings, and generate the project structure.

After generating the project, locate the build.gradle file and update it with any additional dependencies or plugins required for your application. This file serves as the configuration for your build system.

Create a Controller Class for API

To handle API requests, create a controller class in your Spring Boot project. This class will define the endpoints and their associated request-handling methods, allowing you to interact with your backend API.

@RestController
@RequestMapping("e3docs")
public class E3DocsController {
 @GetMapping("/getlist")
 public List<String> getList() {
  List<String> list = new ArrayList<String>();
  list.add("India");
  list.add("China");
  list.add("United States(US)");
  list.add("Russia");
  list.add("Australia");
  list.add("African");
  list.add("Europe");
  return list;
 }
}

Create a Filter Component for Next.js Integration

For smooth integration between the Spring Boot backend and the Next.js frontend, create a filter component. This component will intercept requests and perform necessary actions like direct URL entry or page refresh.

@Component
public class PageRefreshFilter implements Filter {
    private static final String PAGE = "/pagerefresh/pagerefresh.html";
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        doFilter((HttpServletRequest) request, (HttpServletResponse) response, chain);
    }
    private void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        String path = request.getServletPath();
        if ("/".equals(path) || path.contains(".") || path.contains("e3docs")) {
            chain.doFilter(request, response);
        } else {
            request.getRequestDispatcher(PAGE).forward(request, response);
        }
    }
}

Integrate the Frontend with the Backend

Copy the static content from the “out” folder of the Next.js project into the Spring Boot project’s /src/main/resources/static folder. This ensures that the frontend assets are accessible from the Spring Boot server.

Build the Spring Boot project by running the following command:

gradlew clean assemble

After you've successfully finished building the project, you'll find a zip file in the "build/distributions" directory. Unzip the contents of this file and run the appropriate script, like a batch file (e.g., .bat), to start the Spring Boot server.

Once the server is up and running, you can access your application by opening your web browser and entering the following URL: http://localhost:8080. This lets you interact with your Spring Boot application smoothly.

For a more comprehensive guide with detailed steps, specific configurations, and troubleshooting tips, please check out the complete article mentioned below

Creating a Fullstack Web Application with Spring Boot and Next js

Happy coding!😃

Did you find this article valuable?

Support Himanshu by becoming a sponsor. Any amount is appreciated!