Nextjs routing issue: superior param is weird - javascript

I have a project using nextjs v12
I have 2 routes that are overlapping in a weird way.
/:academy/:course
/questions/:id
when I load /questions/1 it works as expected
when I load /mit/math it works as expected
The issue:
when I redirect from /questions/1 to /questions/2,
it loads, you guessed it, the other route! (/:academy/:course)
and more, when I refresh the page (after the redirect) it will load the /questions/:id!!!
I tried
check for miss spelling
make /questions/:id -> /aquestions/:id
so, do you know a way to solve this issue?
thanks.
Solved
it was /q/:id and I renamed it to /q/:id.
and because it's with ssr (I think), I had to clear the cache and restart the project.

This should not happen, because according to official nextJS docs,
Predefined routes take precedence over dynamic routes and dynamic
routes over catch-all routes.
https://nextjs.org/docs/routing/dynamic-routes
In this case, it looks like we are trying to use 2 partial dynamic path, that is why nextJS is not able to figure out the correct path, you can add rewrite rule to always send /questions/* paths to /questions/:id
https://nextjs.org/docs/api-reference/next.config.js/rewrites
Can you please share the code how you are redirecting, to help you better?

Related

Different slug names for the same dynamic path stackoverflow, redirect Nextjs

I have a project that has links for categories and products (see below) and I have to rewrite the project using nextjs, but I have to keep the links (it's important for SEO)
root:
[category] # e.g.: https://domen.com/categoryslug-category-id-103
[product] # e.g.: https://domen.com/productslug-product-id-3663267
But we know that nextjs doesn't allow you to have more then one dynamic page in the same folder.
I understood that with nextjs methods it's impossible (e.g. redirects in next.config.js). Or possible?
I thought about making just one general dynamic page (e.g. [dynamic]) and using different conditions to handle different links/pages in this page, but it will be very big file and it seems not good practice. (I haven't yet tried it, it was just idea, bad idea I guess)
Maybe I have to have the traditional nextjs structure:
root:
category:
[categorySlug] # e.g.: https://domen.com/category/categoryslug-category-id-23
product:
[productSlug] # e.g.: https://domen.com/product/productslug-product-id-3663267
and then somehow to 301 redirect from https://domen.com/category/categoryslug-category-id-23 to https://domen.com/categoryslug-category-id-23, but how?
Just in case: I use Django REST framework as a backend.
Maybe the only way is to get rid of Next.js and use just React? I am newbee and don't now whether it will be possible to have this flexibility with row React AND it's crutual if it's possible to set ssr, ssg without next.js using jast React and if so, how? But would want to remain with Next.js because it has a lot of good fiatures for SEO from the box. But the sake of handling my issue I am ready to get rid of Next.js :(
I heard that it can be done by NGINX (I don't plan to use Vercel server, at least for now I don't think about it). If I have only this option, can you give me a tip/link how to do it.
By this link https://github.com/vercel/next.js/issues/9130 I maybe found the solution (by BramDecuypere), but I don't understand one: "What we do now though (for blogs at least), is have them come from our CMS and store the alternate links of the blogs inside the page as well. So we know there is always a link we can refer too."
What would you do if you had the same task/issue?
I used middleware:
https://nextjs.org/docs/advanced-features/middleware#conditional-statements
import { NextResponse } from "next/server";
import { NextRequest } from "next/server";
export function middleware(request) {
if (request.nextUrl.pathname.includes("category-id")) {
const [slug] = request.nextUrl.pathname.split("-");
return NextResponse.rewrite(new URL(`/category${slug}`, request.url));
}
if (request.nextUrl.pathname.includes("product-id")) {
const [slug] = request.nextUrl.pathname.split("-");
return NextResponse.rewrite(new URL(`/product${slug}`, request.url));
}
}
when you access https://domen.com/categoryslug-category-id-103, it will use /category/[categorySlug] page
the url is still https://domen.com/categoryslug-category-id-103
Then, to avoid duplicates, I wrote in next.config.js the appropriate 301 redirects
to redirect from links like /category/[categorySlug] to like https://domen.com/categoryslug-category-id-103

React router V4 / V5 / V6 nested routing 404 net::ERR_ABORTED 404,

I have tested everything described below with both react router V4 and V5. In V4 the error is just 404, but in V5 it also includes net::ERR_ABORTED.
I am creating a React app with React router. I need to have a /test route and /test/:param1/:param2 route.
First route is OK, but when I created the second and navigated the browser to localhost:8080/test/something/something2 I received a blank page with error in the console saying that it failed to GET localhost:8080/test/something/index.js.
I am using webpack and webpack-dev-server. I then tested more:
Tried to put the second route inside the component of the first.
Tried simplifying the route to /test/:param1, but that didn't work either.
I then tried just a normal 1 level nested route /test/test2(no parameters) and still got the error in the title.
I have also configured a 404 page, however it is displayed only if the path is 1 level: /{something that does't exist}. If I navigate to /{something}/{something more} I get the same ERR_ABORTED.
For some unknown to me reason the browser tries to GET /test/index.js, which obviously doesn't exist.
I spent a day looking through articles, tutorials, and the react router documentation, but everywhere nested routes just work. In fact there is absolutely nothing about this error.
Edit1: After some more testing I've been able to narrow down the issue to just one question: How to configure react-router to always look for the bundle at {domain, localhost:port}/index.js?
Edit2: Tested it with the beta of V6 - same result.
Another is to check if you have in the Webpack config the following:
output: {publicPath: '/'},
Took me some time.
After a few hours I finaly figured it out!! The mistake was so dumb. In my index.html file I required the bundle with <script src="./index.js"></script>. Simply removing the dot fixed the issue. If somebody has the same error, first check your index.html.

Problems with Now 2 migration

As stated here on Spectrum, I'm having troubles in migrating my Next website from an Express custom server to Now. My problem is that I'm unable to get the home page, because I'm trying to send URL params, with no success. I need to pass a lang parameter, as follows:
localhost:3000/en
Then, I would have to get the Home as expected. But I'm receiving this exception:
TypeError: Cannot read property 'lang' of undefined at Function.getInitialProps (/Users/lucacattide/Vagrant/debian/public/LC/front-end/.next/server/static/development/pages/_document.js:1111:32)
That's because I was previously reading the ctx.req.params.lang parameter from _document.js getInitialProps for various reasons. Even by replacing it with ctx.req.query.lang I'm still getting it.
I'm currently copying two examples both by Zeit migration guide and article. As both suggest, I'm trying the API approach (https://zeit.co/guides/migrate-to-zeit-now/) and the pages one too (https://zeit.co/guides/custom-next-js-server-to-routes/).
In the API one, I've implemented inside /api path, the [lang].js segment, with the following content:
module.exports = (req, res) => {
res.send(req.query.lang);
}
Then with the /pages one, I copied and renamed the index.js to [lang].js inside the same path, and replaced the req.query.lang as mentioned above. Both of these doesn't work. I'm stuck with the same exception, that warns about _document.js. I need that because of different processes inside it, so deleting it isn't an option in my case.
Of course I'm testing on Now environment (running now dev) on my localhost. The app works perfectly on Express, so I hope to solve this issue in order to deploy it correctly on Now.
Anyone experienced this before or could help me with some suggestion?
Thanks in advance for support.
EDIT:
I tried to force paths too by defining routes in now.json but the result is the same. Here my current configuration:
{
"public": false,
"name": "LC",
"version": 2,
"routes": [{
"src": "/(?<lang>[^/]+)",
"dest": "/?lang=$lang"
}]
}
EDIT 2:
I switched all inside pages dir as suggested from 2nd guide, because I wasn't getting nothing from /api. Trying by placing only a [lang].js route and removing routes definitions from now.json.
At this moment, by inspecting the req object I receive an empty one.
If you are using the passing the lang like this localhost:3000/en then use below snippet to access this
req.params.lang
But if you are passing the lang like this localhost:3000?lang=en
Then use this
req.query.lang
Due to Now platform updates - v2 - I noticed that a lot of Next API parts has changed. By revamping my code in order to following the new approaches, I'm able to get the previously missing parameter.
In details, I followed the API routes tips on the latest official documentation
Thanks everyone for the help.

react-router v4 + electron - Does a timeline exist where they play nice together?

I'm trying to use react-router v4 inside an electron app.
Issue number one: electron loads the initial page as file:///path/to/project/index.html, react-router expects the initial page to be "/" and as such doesn't match it and renders nothing.
My initial solution to this was this little nasty piece of code to redirect to the right page on app start:
{window.location.href.endsWith('index.html') && <Redirect to="/" />}
This works perfectly until webpack-dev-server pops up to ruin the party - as soon as I make a single change to the code and webpack reloads the page to show the latest changes, it tries to load the new file:/// route, erroring out and showing a blank page.
Anyone ever dealt with this? Are we just doomed to an endless loop of manual electron restarting?
In case anyone ever stumbles upon this, I "solved" the issue using MemoryRouter instead.
This problem is due to the wrong link between the build folder & entry point of your app...
Try the following ways, it will definitely solve your error
DON’T USE in this way
win.loadURL(isDev ? ‘http://localhost:3000' : file://${path.join(__dirname, ‘../build/index.html’)});
USE IN THIS WAY
win.loadURL(isDev ? ‘http://localhost:3000' : file://${__dirname}/../build/index.html);
and if you use React router you must replace BrowserRouter with HashRouter
If your error is solved, Please upvote my answer, hehe

How to get my 404 page to show after upgrade of Sails.js to 0.10.x?

I've upgraded my Sails.js app to 0.10.x and now when I point my browser at a non-existent route such as http://localhost:1337/notfound instead of my views/404.jade being served up I just get a bit of JSON
{
"status": 404
}
I built a default new sails app sails new dummy --template=jade just to compare and contrast with what I have in my existing app, and the only obvious difference I see is that in dummy/config/ there is a file called http.js
I've copied that file over to my app but it's made no difference.
I've also ensured that the tasks in dummy/tasks are identical to my own app's tasks.
In dummy/config/routes.js it says
Finally, if those don't match either, the default 404 handler is triggered.
See config/404.js to adjust your app's 404 logic.
Which is obviously out of date as 0.10.x apps use the api/responses mechanisms.
So I am at rather a loss as to how to get this to work.
I am using 0.10.0-rc8 (and I have confirmed that this is the same in my dummy app as well as my actual app)
Well I've fixed this but I have no idea why it was happening.
To fix it I created a new project as per the method described in my question, but with the same name as my existing project, then, file-by-file, I painstakingly moved across everything specific to my app, taking care to leave in place anything new generated by sails.
Once I'd done that I ran my tests - all passed - and then sails lift and tried it, and yay, everything worked and I got my 404 error page back.
I committed my changes and then carefully picked through a comparison of what had changed.
Alas nothing at all stands out, so, while I have solved my problem, I have no idea what the original cause was.
From the section in the migration guide on "Custom Responses":
In v0.10, you can now generate your own custom server responses. See
here to learn how. Like before, there are a few that we automatically
create for you. Instead of generating myApp/config/500.js and other
.js responses in the config directory, they are now generated in
myApp/api/responses/. To migrate, you will need to create a new v0.10
project and copy the myApp/api/responses directory into your existing
app. You will then modify the appropriate .js file to reflect any
customization you made in your response logic files (500.js,etc).
Basically, v0.10.x gives you more freedom in how things like res.notFound, res.serverError and even res.ok() (success response) work, but you need to copy over the new api/responses folder to migrate.
I had the same issue but was using 0.9.x. Probably a better solution but I outputted a view instead of JSON in all cases.
Update config/404.js to replace res.json() with res.view():
if (err) {
//return res.json(result, result.status); }
return res.view('404') // <-- output the 404 view instead
}
Then, just make sure in your routes.js file it will redirect the /404. Place the following at the bottom of your routes.js file:
'/*': {
view: '*'
},

Categories

Resources