Need help about nextjs dynamic url - reactjs

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}}}

Related

How to server-side render a specific route in 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");
});

Unable to rewrite url in Next.js

I am unable to rewrite the request url below is how my next.config looks
module.exports = withPlugins([
...
{
async rewrites() {
console.log("Rewrites called");
console.log(process.env.NEXT_PUBLIC_DOCS_URL)
return [
{
source: '/docs',
destination: process.env.NEXT_PUBLIC_DOCS_URL,
}
]
}
console logs are correctly printed with new urls but the component is not getting updated with correct links :
<Link href="/docs">
<Button className={NavbarClasses.button}>
<Box color={navWhite ? 'black' : 'white'}>Docs</Box>
</Button>
</Link>
The contents of .env file is as below:
NEXT_PUBLIC_DOCS_URL = http://localhost:4000/docs/intro
But the Link is rendered as localhost:3000 instead of localhost:4000.
Thanks.
According to the Next.js documentation:
Rewrites act as a URL proxy and mask the destination path, making it
appear the user hasn't changed their location on the site. In
contrast, redirects will reroute to a new page and show the URL
changes.
In the nutshell, when user opens your /docs page on localhost:3000 Next.js will send a request on his behalf to localhost:4000 and pass back response. From user's perspective, it looks like localhost:3000 is producing it.
If it's crucial for you to retain original URL, you should use redirects.
Redirects allow you to redirect an incoming request path to a
different destination path.

React Router Dom hitting wrong endpoint

I have a redux action which fires whenever a user on a site tries to change their profile. It does this through an api call middleware that I wrote using a tutorial from Mosh.
export const updateUserProfile =
({ id, name, email, favouriteThing, password, confirmPassword }, headers) =>
(dispatch) => {
dispatch(
apiCallBegan({
url: `api/users/profile`,
data: { id, name, email, favouriteThing, password, confirmPassword },
headers,
method: 'put',
onStart: userUpdateRequested.type,
onSuccess: userUpdateReceived.type,
onError: userUpdateFailed.type,
})
);
};
The app routes are like this:
<Route path='/profile' render={ProfileScreen} exact />
<Route path='/profile/page/:pageNumber' render={ProfileScreen} exact/>
I have pages on the profile page route because I have a React component which displays all the items that the user has created in a table, and I need the table to handle multiple pages. I couldn't figure out how to make a single component within a page change pages without changing the whole page, so I made it that the whole page changes.
The endpoint is this:
router
.route('/profile')
.put(protect, updateUserProfile);
I submit the new data using a submit handler which looks like this:
const submitHandler = (e) => {
e.preventDefault();
if (password !== confirmPassword) {
setMessage('Passwords do not match');
} else {
dispatch(updateUserProfile(data, headers));
}
};
This all works fine when I am at this URL: http://localhost:3000/profile
When I go to page 2 of the profile this is the URL: http://localhost:3000/profile/page/2 and I get the following error:
404 Not Found trying to reach /profile/page/api/users/profile
I logged location.pathname when the submitHandler is triggered and I get '/profile' which appears correct.
However when I log the req.originalURL at the error middleware in express I get /profile/page/api/users/profile
So something is changing the originating URL between when the function is called in the frontend and how it is received in the backend.
Is there anyway to keep req.originalURL at '/profile' irrespective of what page of the profile I am on? I have tried using the Switch component in React Router Dom and setting the location of profile pages route to '/profile' but this breaks the profile pages route and the profile page won't load at all when you click on next page.
I've done a lot of googling and testing in the app and I can't seem to think of anything, which makes me think I have a fundamental misunderstanding of what is going on here. I'd really appreciate some help if someone has any thoughts.
Turns out it was a very simple fix that someone pointed out to me on another site. Thought I would share it here.
There needs to be a forward slash at the beginning of the url in the request, otherwise it is interpreted as a relative path.
url: `/api/users/profile`

React Router cannot GET /route only after deployed to Heroku

I have a simple web-app made with create-react-app and express.
All of the pages made with react router work fine locally, as well as online on my own machine once deployed to Heroku.
But, after testing online on other machines, I can't access these pages - whenever I click the links to them it displays Cannot GET /*route*
I still have the *name*.herokuapp.com domain if that affects it in any way
The redirect code I use is as follows: (I use firebase and react-bootstrap as well)
class App extends Component {
render() {
return (
<div>
<MyNavbar/>
<Switch>
<Route exact path="/" component={Home}/>
<Route exact path="/eateries" component={Eateries}/>
<Route exact path="/thank-you" component={ThankYou}/>
</Switch>
</div>
);
}
Redirecting to /thank-you:
componentWillMount() {
firebase.auth().onAuthStateChanged((user) => {
if (user) {
window.location = "thank-you"
}
})
}
So essentially when a user signs in through a modal component it should take them to /thank-you
Redirecting to /eateries:
<NavItem href="/eateries">
For Eateries
</NavItem>
Is there something wrong with the way I'm redirecting users or using react router in general?
It's hard to know without seeing your server code - but in order to support react-router's rendering mechanism, you need to use a wild card route in your server code:
app.get('*', (req, res) => res.sendFile(path.resolve('build', 'index.html'));
This basically means "for any route not already matched, send the index.html file", which will then load your webapp, which in turn will handle routing. Note that you need to add the static middleware serving your assets before this - that's a gotcha I've forgotten many times. Most of your server file would then look like this:
const express = require('express');
const app = express();
app.use(express.static('build'));
app.get('*', (req, res) => res.sendFile(path.resolve('build', 'index.html'));
app.listen(process.env.PORT, () => console.log('listening for connections'));
Now, this would seem to work either way locally, since your web app is already loaded, and handles routing for you.
However, I've noticed that you're using window.location when redirecting your user. This makes some browsers at least (probably all) request the new page from the server, instead of letting the app deal with it. Instead, use the provided history property, which contains a push method.
componentWillMount() {
firebase.auth().onAuthStateChanged((user) => {
if (user) {
this.props.history.push('/thank-you');
}
});
}
This adds a new entry to the history stack. If you want a regular redirect, you should use .replace instead.
Hope this helps!

Refreshing a react router page that has a dynamic url/params

I have several components displayed with react router that have dynamic url paths. An example path I have is
<Route path="/newproject/:id" onEnter={checkSesh} component= {ProjectDetails} />
When entering this component, I have a componentWillMount function that extract the id part of the url so that I can get the info for the correct project and render it on the ProjectDetails component.
componentWillMount() {
var id = this.props.router.params.id
this.props.teamDetails(id);
}
this.props.teamDetails(id) this calls a redux action creator that will make an axios request to an express route that will get the project info from the database.
export function teamDetails(id) {
return function(dispatch) {
axios.get('/getteaminfo/' + id)
.then(res => {
dispatch({ type: "SET_TEAM_DETAILS", payload: {
teamInfo: res.data.teamInfo,
admin: res.data.admin,
adminID: res.data.teamInfo.teamAdmin,
teamMembers: res.data.teamInfo.teamMembers
}
})
});
}
}
everything works fine upon visiting the page after already being logged in etc. But when I refresh the page /newproject/:id, i get an error Uncaught SyntaxError: Unexpected token <. An example url in my browser looks like http://localhost:3000/newproject/58df1ae6aabc4916206fdaae. When I refresh this page, I get that error. The error is complaining about my <!DOCTYPE html> tag at the very top of my index.html for some reason. This index.html is where all of React is being rendered.
When page is refreshed store state is not preserved. Make sure the state is not important to load the page, or at least initialized properly every time.
For e.g. login information if saved in store and not on browser with localStorage or cookies etc.. then on refresh, the error will come when trying to access /getteaminfo/ route through axios. The response will have error html and it can't be parsed by js.
Please check your web console on for more information. You can use chrome extension like https://github.com/zalmoxisus/redux-devtools-extension which will show your store and etc..
Make sure to check what /getteaminfo/ gives with id is not passed.
Also, make sure on your server side, did you route requests to react-router path through something like this?
e.g. express js,
app.get('*', function response(req, res) {
res.sendFile(path.join(__dirname, 'public', 'index.html'));
});
be sure to sendFile with the real location of index.html
I found the answer here: react-router dynamic segments crash when accessed I added <base href="/" /> into the <head>of my index.html. You can also read more info here: Unexpected token < error in react router component

Resources