history.push in react router fires new request, nginx return 404 - nginx

I read a lot of questions about 'history.push nginx react-router' but I didn't find the solution for the problem I'm facing.
The problem is, when I log in my application in my Login component I do something like this after the ajax call is executed:
cb = (res) => {
if (res.token!== null && res.token !== undefined){
localStorage.setItem("token",res.token);
localStorage.setItem("expiresIn",res.expiresIn);
localStorage.setItem("email", res.email);
**history.push('/home/0/0');**
}else{this.setState({errorTextMail:"wrong mail or wrong password!"})}}
Locally it works fine but in the console the history.push('/home/0/0') fires a request that nginx doesn't handle and return 404, but in my browser the app log me in and I don't see the error.
Instead when I build the app and put the build folder under nginx to serve static files, when I try to login it show me the 404 page. Then if I refresh the page (removing the /home/0/0 from the url) it works fine, recognize the token and log me in and I can browse other route of the app.
I was supposed that history.push would have been handled by react-router, just changing the component mapped by the appropriate <Route path="/home/:idOne/:idTwo" component={Home} /> component and not firing a new request to nginx.
My question is, there is a way to switch compoent when the cb function return my token instead of using history.push('/home/0/0')?
Note the history object is defined this way
import history from './history';
and the history.js's content is :
import createHistory from 'history/createBrowserHistory'
export default createHistory({
forceRefresh: true
})
Thanks for any suggestion.

Related

Discord Oauth2 API request return empty query param

I am implementing discord oauth2 in nextjs and I am having a problem when I deploy to amplify, it works fine in my localhost but it fails in production, my implementation looks like this in the profile page for someone to link their discord account
<a className="text-indigo-800" href={`https://discord.com/api/oauth2/authorize?client_id=${NEXT_PUBLIC_DISCORD_API_ID}&redirect_uri=${NEXT_PUBLIC_DISCORD_REDIRECT_URI}&response_type=code&scope=identify`}>
{" "}{userData.discordUsername || 'Link account'}
</a>
this creates a link that someone can click and they are taken to discord to authenticate, till there everything seem ok, the problem comes now when discord redirects to /api/verify-acount
which looks like this
const discordLink = async (req: NextApiRequest, res: NextApiResponse) => {
console.log("query", req.query);
}
as you can see I ended up knowing the error was here coz I logged req.query which return an object in localhost with the code for user query { code: 'somecode' } but in amplify after going to couldwatch to see the logs then the object is empty
this ends up messing up everything from there as the code is not available to verify and get user details to store in the database.
what I don't know is exactly what caused this error.
I hope someone has idea and will be willing to help thanks
the issue was actually weird and I still don't understand why it had to happen
but my redirect domain was https://subdomain.domain.zyx which amplify accepts and redirects requests to https://www.subdomain.domain.zyx which is the accepted link in the browser (users will always see this even if they enter the first URL) coz of the explained scenario (no www prefix for one of them)
so I was requesting to link discord from https://www.subdomain.domain.zyx and discord would redirect to https://subdomain.domain.zyx and AWS would redirect to https://www.subdomain.domain.zyx so what I still don't understand is where the query params got lost in these steps but after changing redirect URL in discord to https://www.subdomain.domain.zyx then everything works fine now

What path should I use for Meteor's Webapp API?

I'm using Meteor v1.9 Webapp API to have my app listen to HTTP requests, specifically from a link to the app itself from a website, let's say example.org.
The documentation says to use
WebApp.connectHandlers.use([path], handler)
Where the [path] is defined as such:
path - an optional path field. This handler will only be called on
paths that match this string. The match has to border on a / or a ..
For example, /hello will match /hello/world and /hello.world, but not
/hello_world.
My question:
Let's say my meteor application is hosted on abc.com and the POST data being sent over to it is from example.org (where the link to abc.com is as well).
For the [path] argument mentioned above, in this case, should I have it as "/example" since example.org is where my app is listening to requests from (getting the POST data)? Or does it have to be a different format? I tried the former, but it doesn't seem to be working for it, so I'm trying to find the root of the issue.
Additional information that might be useful: I know it says 'optional' so I tried omitting it, but when I tested it out via 'meteor run' where it runs off of localhost:3000, it just yielded a blank page, with no errors and a success sent back, probably because it uses a GET request instead of POST.
My code for the webapp in my meteor application is as follows:
WebApp.connectHandlers.use("/[example]", async (req, res, next) => {
userName = req.body;
res.writeHead(200);
res.end();
});
Also technically my meteor application is built/bundled and deployed as a Node.js application on the website, but that shouldn't affect anything regarding this as far as I could tell.
That path is the path (part of the URL) on your meteor server. So in your example, for instance,
WebApp.connectHandlers.use("/example", async (req, res, next) => {
userName = req.body;
res.writeHead(200);
res.end();
});
means that you will need to send your POST requests to abc.com/example.

Next.JS - localhost is prepended when making external API call

I got a simple Next app where I'm making an external API call to fetch some data. This worked perfectly fine until a couple days ago - when the app is making an API request, I can see in the network tab that the URL that it's trying to call, got Next app's address (localhost:3000) prepended in front of the actual URL that needs to be called e.g.: instead of http://{serverAddress}/api/articles it is calling http://localhost:3000/{serverAddress}/api/articles and this request resolves into 404 Not Found.
To make the API call, I'm using fetch. Before making the request, I've logged the URL that was passed into fetch and it was correct URL that I need. I also confirmed my API is working as expected by making the request to the expected URL using Postman.
I haven't tried using other library like axios to make this request because simply it doesn't make sense considering my app was working perfectly fine only using fetch so I want to understand why is this happening for my future experience.
I haven't made any code changes since my app was working, however, I was Dockerizing my services so I installed Docker and WSL2 with Ubuntu. I was deploying those containers on another machine, now both, the API I'm calling and Next app are running on my development machine directly when this issue is happening.
I saw this post, I confirmed I don't have any whitespaces in the URL, however, as one comment mentions, I installed WSL2, however, I am not running the app via WSL terminal. Also, I've tried executing wsl --shutdown to see if that helps, unfortunately the issue still persists. If this is the cause of the issue, how can I fix it? Uninstall WSL2? If not, what might be another possible cause for the issue?
Thanks in advance.
EDIT:
The code I'm using to call fetch:
fetcher.js
export const fetcher = (path, options) =>
fetch(`${process.env.NEXT_PUBLIC_API_URL}${path}`, options)
.then(res => res.json());
useArticles.js
import { useSWRInfinite } from 'swr';
import { fetcher } from '../../utils/fetcher';
const getKey = (pageIndex, previousPageData, pageSize) => {
if (previousPageData && !previousPageData.length) return null;
return `/api/articles?page=${pageIndex}&limit=${pageSize}`;
};
export default function useArticles(pageSize) {
const { data, error, isValidating, size, setSize } = useSWRInfinite(
(pageIndex, previousPageData) =>
getKey(pageIndex, previousPageData, pageSize),
fetcher
);
return {
data,
error,
isValidating,
size,
setSize
};
}
You might be missing protocol (http/https) in your API call. Fetch by default calls the host server URL unless you provide the protocol name.
Either put it into env variable:
NEXT_PUBLIC_API_URL=http://server_address
Or prefix your fetch call with the protocol name:
fetch(`http://${process.env.NEXT_PUBLIC_API_URL}${path}`, options)

How to fix "Callback URL mismatch" NextJs Auth0 App

I am using Auth0 NextJs SDK for authentication in my NextJS App. I am following this tutorial https://auth0.com/blog/introducing-the-auth0-next-js-sdk/. In my local machine, everything works fine.
The configuration for Auth0 in my local server:
AUTH0_SECRET=XXXXX
AUTH0_BASE_URL=http://localhost:3000
AUTH0_ISSUER_BASE_URL=https://myappfakename.us.auth0.com
AUTH0_CLIENT_ID=XXXX
AUTH0_CLIENT_SECRET=XXXX
In the Auth0 Dashboard, I added the following URLs :
Allowed Callback URLs: http://localhost:3000/api/auth/callback
Allowed Logout URLs: http://localhost:3000/
My local app works locally fine.
I uploaded the app on Vercel. And changed the
AUTH0_BASE_URL=https://mysitefakename.vercel.app/
In Auth0 Dashboard, updated the following information:
Allowed Callback URLs: https://mysitefakename.vercel.app/api/auth/callback
Allowed Logout URLs: https://mysitefakename.vercel.app
I am getting the following error:
Oops!, something went wrong
Callback URL mismatch.
The provided redirect_uri is not in the list of allowed callback URLs.
Please go to the Application Settings page and make sure you are sending a valid callback url from your application
What changes I should make it works from Vercel as well?
You can try to check if vercel isn't changing the url when redirecting to auth0. Your configurations seems good to me. The error is very explicit though. I think a good option should be to verify that the redirect (if handled by vercel) is doing with the same url as auth0 expects.
And don't forget to add the url you're currently on when performing the callback. Are you in https://mysitefakename.vercel.app/api/auth/callback when the callback is executed? (call auth0).
you have to change your base url in the env.local file
AUTH0_BASE_URL=https://mysitefakename.vercel.app/
you can also make two more env files namely env.development and env.production and set different base urls for different cases so that the correct base url is automatically loaded depending on how ur web app is running.
You need to add handleLogin under api/auth/[...auth0].js and that will solve it:
import { handleAuth, handleLogin } from '#auth0/nextjs-auth0';
export default handleAuth({
async login(request, response) {
await handleLogin(request, response, {
returnTo: '/profile',
});
},
});
Don't forget to also add allowed callback url in [Auth0 Dashboard]: https://manage.auth0.com/dashboard for your hosted app for both local and hosted instance:
http://localhost:3000/api/auth/callback, https://*.vercel.app/api/auth/callback

Nuxt Middleware with Firebase and FirebaseUI: Error: Redirected when going from "/anything" to "/login" via a navigation guard

Nuxt SSR app using FirebaseUI to handle auth flows. Logging in and out works perfectly. When I add Middleware to check auth state and redirect if not logged in I get this error:
Error: Redirected when going from "/list-cheatsheets" to "/login" via a navigation guard.
middleware/auth.js
export default function ({ store, redirect }) {
// If the user is not authenticated
if (!store.state.user) {
return redirect('/login')
}
}
There is absolutely no other redirecting that I can find in the app....
I have been digging and trying things for hours. Others who get this error that I have found aren't using Nuxt and none of those solutions work.
As there is a bounty one cannot mark it duplicate thus following up is a copy of my answer at Redirecting twice in a single Vue navigation
tldr: vm.$router.push(route) is a promise and needs to .catch(e=>gotCaught(e)) errors.
This will be changed in the next major#4
Currently#3 errors are not distinguished whether they are NavigationFailures or regular Errors.
The naive expected route after vm.$router.push(to) should be to. Thus one can expect some failure message once there was a redirect. Before patching router.push to be a promise the error was ignored silently.
The current solution is to antipattern a .catch(...) onto every push, or to anticipate the change in design and wrap it to expose the failure as result.
Future plans have it to put those informations into the result:
let failure = await this.$router.push(to);
if(failure.type == NavigationFailureType[type]){}
else{}
Imo this error is just by design and should be handled:
hook(route, current, (to: any) => { ... abort(createNavigationRedirectedError(current, route)) ...}
So basically if to contains a redirect it is an error, which kinda is equal to using vm.$router.push into a guard.
To ignore the unhandled error behaviour one can pass an empty onComplete (breaks in future releases):
vm.$router.push(Route, ()=>{})
or wrap it in try .. catch
try {
await this.$router.push("/")
} catch {
}
which prevents the promise to throw uncaught.
to support this without redirecting twice means you put the guard to your exit:
let path = "/"
navguard({path}, undefined, (to)=>this.$router.push(to||path))
which will polute every component redirecting to home
btw the router-link component uses an empty onComplete
Assumption that redirecting twice is not allowed is wrong.

Resources