Cookies not sent with cross-origin-request - axios

After days of searching and trying, I'm here now.
I deployed the React Application in Netlify and the Node.js backend in Heroku. Everything works fine in localhost environment. But after deploying, cookies are not sent in request header.
CORS:(Backend Node.js)
app.use(cors({
origin: CORS_ORIGIN,
credentials: true,
allowedHeaders: "Content-Type,Accept,User-Agent,Accept-Language,Access-Control-Allow-Origin,Access-Control-Allow-Credentials,cache-control"
}));
Axios:
import axios from "axios";
axios.defaults.withCredentials = true;
export default axios.create({
baseURL: process.env.REACT_APP_BACKEND + "/api",
headers: {
"Content-type": "application/json",
"Access-Control-Allow-Origin": process.env.REACT_APP_BACKEND,
},
});
Fetching Data(Mutation): apiClient is imported from above Axios.js and cookies is handled by react-cookies
apiClient.post("/auth/login",{ email: "name#mail.com", password: "pawspaws" })
.then((res) => {
setCookie("jwt", res.data.accessToken, { path: process.env.REACT_APP_PATH || "/", domain: process.env.REACT_APP_DOMAIN, maxAge: 26000, secure: true, sameSite: 'None' });
setCookie("refresh", res.data.refreshToken, { path: process.env.REACT_APP_PATH || "/", domain: process.env.REACT_APP_DOMAIN, maxAge: 2600000, secure: true, sameSite: 'None' });
setCookie("user", res.data.user, { path: process.env.REACT_APP_PATH || "/", domain: process.env.REACT_APP_DOMAIN, maxAge: 26000, secure: true, sameSite: 'None' });
}).catch((err) => console.log(err.response))
Above code sets the cookies.. and it's working.
Now, below is the request I'm sending which doesn't send the Cookies along with the request:
apiClient.get("/posts/timeline", { params: { email: "name#mail.com" } })
.then((res) => { console.log(res.data); })
.catch((err) => { console.log(err.response) });
Well, it returns unauthorized since the Cookie is not sent at all..

Ok, i found my own solution.. It was pretty easy.. It was setting up proxy
Just added line below to package.json in frontend:
"proxy":"https://random.name.herokuapp.com",
FYI, for Netlify, we need additional _redirects file in public folder.
_redirects
/api/* https://random.name.herokuapp.com/api/:splat 200
/* /index.html 200

In my case I had hardcoded my front end api calls to the herokubackend
axios.get("https://infinite-ocean-8435679.herokuapp.com/api/user")
First removed the hrokupart from the request like this
axios.get("/api/loguserin")
Then added the proxy value to the bottom of the package.json
"proxy":"https://infinite-ocean-8435679.herokuapp.com",
Next added a file called _redirects inside the react public folder.(_redirects is the file name and it has no extension such as .txt so don't add _redirects.txt )
Add the following inside _redirects file
/api/* https://infinite-ocean-8435679.herokuapp.com/api/:splat 200
/* /index.html 200
inside _redirects file formatting will be weird just add above code replacing heroku part with your backend url.
React automatically add all the files inside the public folder to its build folder once created.
deploy the site to Netlify

Related

axios POST get 400

This is driving me crazy!
Exactly the same POST request works fine in Insomina per screenshot below:
The only header Insomina has is: Content-Type: application/json.
Now, the same request in code (I even copied the code generated from Insomnia for axios) via axios in Typescript:
const saveReqConfig: AxiosRequestConfig = {
method: 'POST',
url: 'THE SAME URL USED IN Insomina',
timeout: 3000,
data: {
name: `TestName`,
uri: `TestURI`,
statusCode: '200',
simulatedLatency: '0',
contentType: "application/json",
tags: '',
response: 'testing...',
type: 'VA',
},
headers: {
'Content-Type': 'application/json',
}
}
const normalAxios = axios.create();
const test = await normalAxios.request(saveReqConfig);
Don't understand why I am getting AxiosError: Request failed with status code 400 from code but the same request works fine in Insomina.
I think you did not set the headers correctly or you may not have setup the .create() properly.
Something like this:
const instance = axios.create({
url: '/post',
baseURL: 'https://httpbin.org',
method: 'POST',
timeout: 1000,
headers: {
Content-Type: 'application/json' // <- set your headers
}
});
let res = await instance.request({ // <- pass the data here
data: { // This should be whatever you want to post to this url. I just copied what you had.
name: `TestName`,
uri: `TestURI`,
statusCode: '200',
simulatedLatency: '0',
tags: '',
response: 'testing...',
type: 'VA',
}
});
Are you sure you need to use the .create() factory? The normal post like this might suite your needs better?
const data= { title: 'Axios POST Request Example' };
const headers = {
Content-Type: 'application/json'
};
axios.post('url', data, { headers }).then(response => console.log(response.data.title);
Posting here in case it helps someone.
It turned out that I couldn't post the request programmatically is because of lack of a TLS certificate. I didn't know that Insomnia has the option to disable the TLS and that's why it works in Insomnia.
To disable TLS (Do NOT do this in production!) from node with axios, create an instance of axios with a https agent setting rejectedUnauthorized to false e.g.
const instance = axios.create({
httpsAgent: new https.Agent({
rejectedUnauthorized: false
})
});
Also, set the environment variable as:
process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';

CORS headers missing when using Axios in NextJS

I'm using a NestJS backend with a NextJS frontend, both hosted seperately.
NestJS Backend
I enabled CORS in the backend as follows:
app.enableCors({ credentials: true, origin: process.env.FRONTEND_URL });
When using cors-test.codehappy.dev to check the CORS headers everything looks good. All headers are present and the access-control-allow-origin header points to the right domain where the front-end is hosted on.
NextJS Frontend
On the NextJS frontend I'm using Axios to make request to the backend (the exact same url as used above).However, when creating a request the preflight request in Chrome is missing all CORS headers. The Axios instance below is imported when a HTTP request is needed.
import Axios from 'axios';
const api = Axios.create({
baseURL: process.env.BACKENDURL,
withCredentials: true
});
export default api;
The error in the console:
The preflight request:
in next.config.js
module.exports = {
//avoiding CORS error, more here: https://vercel.com/support/articles/how-to-enable-cors
async headers() {
return [
{
// matching all API routes
source: "/api/:path*",
headers: [
{ key: "Access-Control-Allow-Credentials", value: "true" },
{ key: "Access-Control-Allow-Origin", value: "*" },
{ key: "Access-Control-Allow-Methods", value: "GET,OPTIONS,PATCH,DELETE,POST,PUT" },
{ key: "Access-Control-Allow-Headers", value: "X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version" },
]
}
]
},
}

axios not sending cookie to nestjs from NextJs

Have a front end nextJs running on a different port to the backend nestjs.
Within the nextJs session-cookie I have 2 JWT tokens access and refresh.
I can extract the access token from the next-auth session-token but axios will not send to nestjs.
If I use the { withCredentials: true } the whole next-auth token is sent but if I use the headers object nothing is received
const data = await axios.post(
process.env.NEXT_PUBLIC_SH_API_BASEURL + '/blog',
{ formData },
//{ withCredentials: true }
{
headers: {
Cookie:
'Authentication=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjEzNTQ1N2FiLWI4MGUtNDU2OC1hY2RiLWNiODZmYTJlNGQxMyIsImlhdCI6MTY1MzU0NjM0NiwiZXhwIjoxNjU0NDQ2MzQ2fQ.fvnRXYwheuIOHvlTZRGqBiVR98JxdT7UqZbc6SAvcAk; Path=/; HttpOnly;'
},
}
);
nestJS - log when using with credentials
{
'next-auth.csrf-token': '493deccd24c0165f8afe08db04352415c46c7a6f150f9c51320aea0d5444589d|51953c1c056c986b799afb9dcea8c94469d35b4aab291b02ee343057fa80a70e',
'next-auth.callback-url': 'http://localhost:3000/auth/signin?callbackUrl=http://localhost:3000/',
'next-auth.session-token': 'eyJhbGc
}
But if use the headers I get
[Object: null prototype] {}
The nestJs logging is done using:
jwtFromRequest: ExtractJwt.fromExtractors([
(request: Request) => {
console.log('JWT strategy auth cookie');
console.log(request?.cookies);
return request?.cookies?.Authentication;
},
]),
If I make a call from postman there is no issue with processing the header cookie.
Could you let me know how to get axios to send the header cookie only?
Thanks

How can I reach the 'Retry-After' response header using axios?

I'm building a simple Vue2 app with Auth section, which makes requests to REST API service.
So, I have my axios instance:
const instance = axios.create({
baseURL: BASE_URL,
timeout: DEFAULT_TIMEOUT,
withCredentials: true,
headers: {
accept: 'application/json',
},
});
To make authorization requests I use a separate module:
const auth = (api) => ({
submitPhoneNumber({ userPhone }) {
return api.get(`auth/${userPhone}`);
},
});
And set it all up together like this:
export default {
auth: auth(instance),
};
Then I add my api to Vue as a plugin:
export default {
install(Vue) {
const vueInstance = Vue;
vueInstance.prototype.$api = api;
},
};
In the component I access my api-plugin and make a request, extracting status and headers from it:
const { status, headers } = await this.$api.auth.submitPhoneNumber({
userPhone: this.userPhone,
});
When I look through the response in chrome devtools, I clearly see a "retry-after" header with number of seconds, after which I can make another request.
Upon receiving the response, I would like to save this number of seconds to some variable and then render a warning message like "Please wait { seconds } to make another submit".
The problem is that in my code I have no such header in the response (while I can see it in devtools, a I said):
see the screenshot
So, when logging the headers from my response, there are just these:
{content-length: '19', content-type: 'application/json; charset=utf-8'}
What is the problem with that?
Try var retrysec = error.response.data.retry_after that worked for me

Sails.js CORS for post method

I was able to use CORS for a specific controller using a GET request like the following:
'get /url': {
controller: 'somecontroller',
action: 'someaction',
cors: true
},
However if I try using POST like the following, I get "Access Denied" error:
'post /url': {
controller: 'somecontroller',
action: 'someaction',
cors: true
},
How do I setup cors for a post method?
in config/routes.js before declaring routes put :
'OPTIONS /*': function(req, res) {
res.send(200);
},
and in config/cors.js try to put :
module.exports.cors = {
allRoutes: true,
origin: '*',
credentials: true,
methods: 'GET, POST, PUT, DELETE, OPTIONS, HEAD',
headers: 'content-type, access-control-allow-origin, authorization'
};
With my limited research I found out that simply adding "cors: true" to the controller doesn't solve the problem. Sails is still expecting a csrf token for the post method. In the bootstrap.js file under config folder, I added the following code at the bottom to disable csrf token on the route by using the following:
sails.config.csrf.routesDisabled = '/url';
If you have better solutions, please post them here. Thanks!
Edit: You can also change this in the config/csrf.js file. Change module.exports.csrf = true; to:
module.exports.csrf = {
routesDisabled: '/url',
};
You might have to use it for your apis
module.exports.csrf = {
routesDisabled: '/api/*',
};