How can ExpressJS be used to direct users to individual standalone React applications?

I've spent a lot of time scouring the internet for a solution to my problem, but it seems like maybe I'm not asking in the right way.

My project involves creating a Node-Express website where ReactJS is only needed on specific pages, while the rest are server-side rendered.

For standard pages, I utilize Express and EJS to render the view. However, for pages built with React, I want them to function as individual single-page applications. Essentially, each React-built page should be separate without using React-Router across the entire site. The majority of the website does not require React functionality.

Currently, I am relying on a React CDN, but its capabilities are limited as I cannot npm install pre-made components.

If I want routes "/" and "/app" to be two distinct React apps, with all other routes being server-rendered, how can I achieve this? Should I run create-react-app twice in separate folders, one for "/" and one for "/app"?

Answer №1

Usually, in situations like this, I would recommend setting up a subdomain to segregate the app's logic. For example, if your main domain is example.com, which might be a dynamic website, you could create a admin.example.com subdomain to host your admin dashboard built with React or another single-page framework.

In response to your query, if you must stick to your current approach, the first step is to define a base name within the BrowerRouter of react-router-dom to serve your React app under a specific URL path.

// This configuration will host the react app at example.com/calendar
<BrowserRouter basename="/dashboard">
    <Link to="/today"/> // renders <a href="/calendar/today">
    <Link to="/tomorrow"/> // renders <a href="/calendar/tomorrow">
    ...
</BrowserRouter>

Next, add the following line to your index.html file:

<base href="%PUBLIC_URL%/">

If you need to navigate to a specific URL within your React app, consider creating a separate history.js file:

//history.js
import {createBrowserHistory} from 'history';

export default createBrowserHistory({ basename: 'dashboard'});

Similarly, remember to use the custom history object when defining your routes:

<!-- import the history object and pass it as a prop here -->
<Router history={history}>
  ...
</Router>

Lastly, make sure to update the homepage path in your package.json file to match the base name you previously defined:

//package.json
"homepage": "./dashboard"

Once these steps are completed, you can proceed with setting up your routes as needed. If you're hosting on shared hosting/cPanel, simply upload the build folder to the main route directory of the domain. Alternatively, if you're using self-hosted Linux servers, organize different folders and utilize reverse proxy (Apache/Nginx) to manage traffic redirection according to your requirements. Hopefully, these instructions prove helpful.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Refresh the context whenever the state object changes

Within my application, I am utilizing a PageContext to maintain the state of various User objects stored as an array. Each User object includes a ScheduledPost object that undergoes changes when a user adds a new post. My challenge lies in figuring out how ...

What is the best way to iterate through JavaScript objects within a Jade template?

Technologies such as Node.js, Jade, socket.io, jQuery, and JSON are being used in my project. In my "index.jade" file, I have the following code that receives "results" data as JSON from the backend: extends layout block content ul // more jade html h ...

Developing single-page application frontends without utilizing node or npm

As a backend java developer with experience in spring boot, I am now exploring the world of single page applications. One aspect that appeals to me about SPA frameworks, particularly Vue, is things like model-binding and the use of components and template ...

What can be done to ensure smooth functionality of my nested navigation menu on mobile devices?

I'm utilizing the incredible features of Base Web for my website. One of the components I am using is a menu with a child menu, based on this example. The menu works perfectly fine on desktop - when I hover over an option, the child menu appears. Howe ...

What are the best practices for integrating Quill with Node.js and MongoDB?

I'm in the process of creating my own blog, and I really want to have a user-friendly interface for updating the content instead of manually editing HTML files each time. My plan is to use the Quill editor to create blog posts (which are saved as del ...

The user ID encountered a CastError: Unable to convert the value "64e310ad9d821c557b4f9bc7" (of type string) to an ObjectId for the "userId" path due to a BSONError

When passing the "id" to the hidden input value in EJS, a bson error is encountered. The data is correctly stored in the database, but the error appears in the EJS file. The error occurs in the form.ejs file: form.ejs <!DOCTYPE html> <html lan ...

Prop in a React component is undergoing mutation

I encountered a strange situation where a prop in a React component is being changed. Although it's technically not a mutation since it's an array in JavaScript, it should not be modified. To replicate the issue, I created a simple example: htt ...

Tips for customizing an Alert component in a React Native application

I've been working on developing an Alert element using react-native. I have successfully created it with the following code: Alert.alert( 'Warning', 'bla bla bla', [ {text: 'OK', onPress: () => ...

Troubleshooting a node-gyp issue with Karma

Hi there! I'm facing an issue while trying to set up karma using npm. After fetching the packages, the terminal seems to hang on the final build error message. To install karma, run this command: npm install -g karma During installation, some conso ...

I am looking to change the state of only the element that is being moused over in a React Hooks useState function, rather than changing the

Currently, I have a component from line 61-67 that controls the state of an editIcon. The issue is that it changes the state values for all items in the column, rather than just the specific item or row it should apply to. When hovering over a span element ...

Execute a simulated click on the Material-UI Tabbar using a programmatic approach or keyboard shortcut

In my electron/react application, I am implementing Material UI tabs in the following manner: <Tabs> <Tab label="View1" > <View1 /> </Tab> <Tab label="View2"> ...

Does the express static middleware make a new file read from the disk every time it is accessed by a client?

Utilizing the express static middleware allows me to serve static files, and I also implement the compress middleware. I'm curious if express actually reads the file from disk and compresses it each time before sending it to the client, or if it cache ...

Attempting to display a collection of 16 diverse images by utilizing the Math.random function in conjunction with a

I have been attempting to retrieve 16 random images, but I keep getting duplicates. I am aware that a modification needs to be made to the one => one.number filter, however all attempts so far have been unsuccessful. import React from "react"; import ...

Transferring the user session data from an Express server to the state of a React

I'm currently exploring how to pass the session id to React components. After a user logs in, I want the session id to persist across different pages unless explicitly destroyed. To set up an express session: // setting up express session app.use(se ...

Tips for styling the Button component in the shadcn/ui library for maximum impact

I'm currently working on a project using the shadcn/ui library. How can I properly customize it to meet my specific needs? For example, let's say I require an extra large red rounded Button for a call-to-action button in my project. What would be ...

Strategies for avoiding a hover component from causing distortion to its parent component in React

I am encountering an issue with a hover component that is causing distortion in its parent component when displayed. Essentially, I need to prevent the hover component from affecting the layout of its container. Below is the code snippet: Styling for Lang ...

Ensuring that environment variables are properly set is essential for effective error handling

I am currently integrating my NodeJS and Typescript App to create new config files that utilize .env variables. If a specific variable is not set, I want to trigger an error. After setting up my config file, I encountered some errors; however, I am unsure ...

Encountering an error while setting up the object spread operator Babel plugin for ES201

Exploring the possibilities of the new ES2018 spread operator for objects led me to discovering a promising NPM package: babel-plugin-transform-object-rest-spread Here's a glimpse of my package.json: // Scripts section "scripts": { "dev": " ...

Deployment to DigitalOcean fails due to GitHub action error

I'm encountering an issue during the deployment process to DigitalOcean via github actions and I can't figure out why it's throwing an error related to python. Could this be a result of the docker images I'm utilizing? Despite my attemp ...

[Symbol(errorCode)]: 'INCOMPLETE_MEMBER_DATA' (MyApp)

Here is the code snippet I am working with: import { Client } from 'discord.js'; const bot = new Client(); bot.on('ready', () => console.log('${bot.user.username} is online')); bot.login(&apos ...