How to server-side render a specific route in ReactJS? - reactjs

I would like to server-side render only a specific route in React. For example, /home should be client-side rendered, but /post should be server-side rendered.
The /post route receives a post ID as a parameter(using react-router) and fetches the content from a database server.
Is their any way I can server-side render only a specific page/route using react-dom server?

Your data should be handled by the middleware and stored there to minimize api calls. The Front end should render based on that data.

One good approach is to use built version of your react within express.js server. So let's say you have your built version of your react inside build directory :
var express = require('express');
var app = express();
app.use("/post",function(req,res) {
console.log(req); // Do your stuff for post route
});
app.use("/",express.static(path.join(__dirname,"/build")));
app.use("/*",express.static(path.join(__dirname,"/build"))); // Handle react-router
const httpServer = require("http").createServer(app);
httpServer.listen(8080, function(){
console.log("Server is running on 8080");
});

Related

React App and Express Server routing for a single page application

How do I set the routes for my React Single page application in Express js
Navigate a React App link from a single page application to Express server dynamically
Your question is not completely clear but I'm assuming you want to know how to use express for API routes and still server react on the frontend. If this is the case you can do it like this on your backend file (let's call it server.js). And the react app is in a folder called "client":
const app = express();
// API routes
app.get("/api/test", (req, res) => {
res.send('example response from backend');
});
// If no API routes are hit, send the React app
app.use(function (req: Request, res: Response) {
res.sendFile(join(__dirname, "./client/build/index.html"));
});
Note that you have to send the React app last. This line must come after all other routes.

Nextjs ssr is serving correct data, but page component receives old cached data

My NextJs app has a weird behavior. when i use SSR for rendering page it load the correct data at first, but when i use router.replace(asPath); to refresh the data after inserting a new value to my mongodb database, the ssr fetches new data, but page renders same old data. And if i click on the route link then the correct data is loaded.
Page refreshing code
const router = useRouter();
const { asPath } = router;
router.replace(asPath);

Host react app and laravel backend(Admin panel) in same laravel application project

I want to host the react app and laravel app in the same laravel application project.
The front end app is react and backend(admin panel) laravel.
I want redirect all request to specific front end view except first URL segment == backend/:any
Eg.
http://host.com/backend/(any)
Continue with laravel router
http://host.com/(any) except backend/
Continue with react router
Any idea for that matter?
You have two options here, either pass a regular expression to the any route to ignore API prefixed routes
Route::get('/{any}', function () {
return view('index.blade.php');
})->where('any', '^(?!backend).*$');
Route::fallback(function () {
return view('index.blade.php');
});
From the docs
Fallback Routes
Using the Route::fallback method, you may define a route that will be executed when no other route matches the incoming request. Typically, unhandled requests will automatically render a "404" page via your application's exception handler. However, since you may define the fallback route within your routes/web.php file, all middleware in the web middleware group will apply to the route. You are free to add additional middleware to this route as needed:
Route::fallback(function () {
//
});
The fallback route should always be the last route registered by your application.
Try something like this in the "routes/web.php":
// WRITE BACK-END ROUTES AT FIRST
Route::group([
'prefix' => 'backend',
], function () {
Route::get('/', 'AdminController#dashboard')->name('dashboard');
Route::get('admin-page-1', 'AdminController#page1')->name('page1');
Route::get('admin-page-2', 'AdminController#page2')->name('page2');
// some other admin routes if you need
});
// FRONT ROUTE(S)
Route::get('/{text}', 'FrontController#front')->name('front');

Need help about nextjs dynamic url

I am having this problem that whenever i try to visit the page localhost:3000/blog/test directly it returns a 404 error. But whenever i try to visit it using <Link> component it works fine.
This is my code <Link href={{ pathname: '/blog', query: {slug: 'test'} }} as="/blog/test"><a className="nav__link">Blog</a></Link>
and i have a file blog.js in my pages folder.
What's happening is that on the client, with the Link component, you are creating a link to the blog.js page by setting "/blog" as the pathname.
When you go directly to the URL/blog/test, Next.js will try to render the page on the server and to do so will look for the file /pages/blog/test.js. That file doesn't exist, and Next.js doesn't know that you want to load the blog.js page and set query.slug to to the second part of the URL.
To do this, you need to map that route on the server to load the page you want, and pull the params you want out of the URL.
The Next.js docs cover this in Server Side Support for Clean URLs by using express to setup a custom server.
You can view the full code to get it working there, but your custom route will look something like this:
server.get('/blog/:slug', (req, res) => {
const actualPage = '/blog'
const queryParams = { slug: req.params.slug }
app.render(req, res, actualPage, queryParams)
})
You'll have to use now.json to set up your routes. Also it is important to note that it's now that builds the route so visiting it on the client side wont work if you are using localhost. Build your project with now and it should work.
Also the "as" parameter would be as={{ pathname:/user/manage/${variable}}}

routing of static website using nodeJs

I build a website using angular js. But That is not a SPA. I use angular js for API calling and fetch some data only so now I want to do routing for custom URL of my HTML pages how will I do it ? I am serving my website using nodeJs. is there any configuration in node js to set custom URL of static website/routing.
For using the routes in nodejs you can use express.Router() module.It can be installed same as express and then you can define the routes on that.
For example :-
var adminRouter = express.Router();
adminRouter.get('/',function(req,res){
res.send('Here is the dashboard for my app');
});
adminRouter.get('/users',function(req,res){
res.send('Here is the menu to show all the users');
});
//Now to apply the routes to your app
app.use('/admin',adminRouter);
You can also route the middleware of your app and the url parameters separately

Resources