Redirect with Go and React: Seamless Frontend Routing (2026)

Discover how to configure Go to redirect requests to React's frontend routing, ensuring seamless navigation in your web applications.

Redirect with Go and React: Seamless Frontend Routing (2026)

Redirect with Go and React: Seamless Frontend Routing (2026)

Integrating backend services with a frontend application can sometimes be challenging, especially when it involves routing and redirection. In this tutorial, we will explore how to configure a Go server to handle routing for a React application seamlessly. This is particularly useful when you want to leverage React Router for frontend navigation while utilizing Go for backend logic.

Key Takeaways

  • Learn to configure a Go server to redirect to React frontend routing.
  • Understand how Go handles static files and API requests.
  • Implement a solution that combines Go's backend capabilities with React Router.
  • Discover common pitfalls and troubleshooting tips.

In modern web applications, it is common to separate frontend and backend responsibilities. A typical stack might use React for the frontend and Go as a backend server for handling API requests. However, when deploying such applications, configuring proper routing can be a challenge. This tutorial will guide you through integrating Go's routing capabilities with React Router to create a seamless user experience.

Prerequisites

  • Basic understanding of Go and its HTTP package.
  • Familiarity with React and React Router.
  • Go installed on your machine (version 1.20 or newer).
  • Node.js and npm installed to manage React dependencies.

Step 1: Set Up Your Go Environment

First, ensure that your Go environment is correctly set up. This involves installing Go on your system and setting up the necessary paths.

# Install Go
brew install go # For MacOS
sudo apt-get install golang-go # For Ubuntu

Check your installation:

go version

Ensure your Go version is 1.20 or newer.

Step 2: Create a Simple Go Server

Let's start by creating a simple Go server that serves static files and an API endpoint. Create a new directory for your project and inside it, create a file named main.go.

package main

import (
    "net/http"
    "log"
)

func main() {
    // Serve static files from the build directory
    http.Handle("/", http.FileServer(http.Dir("./build/")))
    
    // Handle API requests
    http.HandleFunc("/my_api", func(w http.ResponseWriter, r *http.Request) {
        w.Write([]byte("Hello from API"))
    })
    
    // Start the server
    log.Fatal(http.ListenAndServe(":8090", nil))
}

This code sets up a basic server that listens on port 8090. It serves static files from the ./build/ directory and handles requests to /my_api.

Step 3: Build Your React Application

Assuming you have a React app ready, build it for production. This will generate the static files that Go will serve.

npm run build

This command creates a build folder with all the necessary files.

Step 4: Configure React Router

Ensure that your React application uses React Router for navigation. Here’s a simple example:

import React from 'react';
import { BrowserRouter as Router, Route, Switch, Link } from 'react-router-dom';

function App() {
  return (
    
      
        
          
            Home
            MyPath
          
        
        
          
          
        
      
    
  );
}

function Home() {
  return Home;
}

function MyPath() {
  return MyPath;
}

export default App;

This setup allows navigation between the home and another path using React Router.

Step 5: Enable URL Redirection in Go

To enable URL redirection so that all non-API requests are handled by the frontend, modify the Go server as follows:

package main

import (
    "net/http"
    "log"
    "os"
)

func main() {
    // Serve static files
    fs := http.FileServer(http.Dir("./build"))
    http.Handle("/", fs)

    // API endpoint
    http.HandleFunc("/my_api", func(w http.ResponseWriter, r *http.Request) {
        w.Write([]byte("Hello from API"))
    })

    // Handle all other routes by redirecting to index.html
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        if _, err := os.Stat("./build" + r.URL.Path); os.IsNotExist(err) {
            http.ServeFile(w, r, "./build/index.html")
        } else {
            fs.ServeHTTP(w, r)
        }
    })

    // Start the server
    log.Fatal(http.ListenAndServe(":8090", nil))
}

This modification checks if the requested path exists. If not, it serves the index.html file, allowing React Router to handle the routing.

Step 6: Test Your Application

Run your Go server and navigate to different routes in your React application. Confirm that API requests are handled correctly and that the frontend routing works as expected.

go run main.go

Open your browser and visit http://localhost:8090/. Try navigating to /my_frontend_path and test the API endpoint at /my_api.

Common Errors/Troubleshooting

  • Ensure that the build directory is correctly populated with the React build files.
  • Check file permissions if static files are not being served.
  • Verify that React Router is correctly configured to handle the routes.
  • If the server is not starting, check for port conflicts or syntax errors in main.go.

Frequently Asked Questions

Why is my API endpoint not working?

Ensure that the API route in your Go server matches the endpoint you're trying to access. Double-check the request URL and method.

How do I handle 404 errors?

Configure your Go server to serve the index.html file for all non-API requests, allowing React Router to manage the routing.

Can I use a different port?

Yes, you can change the port in the http.ListenAndServe function to any available port.

Frequently Asked Questions

Why is my API endpoint not working?

Ensure that the API route in your Go server matches the endpoint you're trying to access. Double-check the request URL and method.

How do I handle 404 errors?

Configure your Go server to serve the index.html file for all non-API requests, allowing React Router to manage the routing.

Can I use a different port?

Yes, you can change the port in the http.ListenAndServe function to any available port.