Nextjs | Set cookies header

Hi, I want to make a call to an API (which I don't have access to) that returns headers with cookies, however the cookies are blocked since the host domain is different. I tried to use rewrite in the config file but it did not change anything, does anyone have a solution?
30 Replies
π›ˆπž‚π—Ώπžˆπ’†π’ˆπ–π°π›ˆ 𝐜0πŸƒ3𝗿
@Zepeto Sounds like you are having a CORS issue, do you have any control over the backend API whatsoever? You have a few options you can try: 1. Use a proxy: One solution is to set up a server-side proxy that makes the API request on behalf of your app. The proxy can then forward the API response back to your app, and include any cookies in the response headers. Since the API request is made from the same domain as your app, the browser will allow the cookies to be set. You can use a library like http-proxy-middleware to set up the proxy in your Next.js app. 2. Use JSON Web Tokens (JWTs): If the API supports JWT authentication, you can use JWTs to authenticate your requests instead of cookies. JWTs are tokens that are signed by the server and can be used to authenticate subsequent requests. You can store the JWT in local storage or a cookie that is accessible to your app's domain, and include the JWT in your API requests. 3. Use CORS headers: If you have access to the API server, you can set the appropriate CORS headers to allow your app's domain to access the API. CORS headers tell the browser to allow cross-origin requests from specific domains. You can set the Access-Control-Allow-Origin header to your app's domain to allow cross-origin requests, and include the Access-Control-Allow-Credentials header to allow cookies to be sent with the request.
Zepeto
Zepetoβ€’15mo ago
No access to the api I used rewrite config in config file but I’m unauthorized since I use it this way
π›ˆπž‚π—Ώπžˆπ’†π’ˆπ–π°π›ˆ 𝐜0πŸƒ3𝗿
Yeah, without more detailed info about the API, it's hard to come up with more specific suggestions, but I would guess #1 is your best bet You could, for example, try nextjs-cors or cors-anywhere.
const cors = require("nextjs-cors");

module.exports = cors({
methods: ["GET", "POST", "PUT", "DELETE"],
origin: "*",
optionsSuccessStatus: 200, // some legacy browsers (IE11, various SmartTVs) choke on 204
});
const cors = require("nextjs-cors");

module.exports = cors({
methods: ["GET", "POST", "PUT", "DELETE"],
origin: "*",
optionsSuccessStatus: 200, // some legacy browsers (IE11, various SmartTVs) choke on 204
});
π›ˆπž‚π—Ώπžˆπ’†π’ˆπ–π°π›ˆ 𝐜0πŸƒ3𝗿
GitHub
GitHub - Rob--W/cors-anywhere: CORS Anywhere is a NodeJS reverse pr...
CORS Anywhere is a NodeJS reverse proxy which adds CORS headers to the proxied request. - GitHub - Rob--W/cors-anywhere: CORS Anywhere is a NodeJS reverse proxy which adds CORS headers to the proxi...
GitHub
GitHub - yonycalsin/nextjs-cors: nextjs-cors is a node.js package t...
:tada: nextjs-cors is a node.js package to provide a Connect/Express middleware that can be used to enable CORS with various options :rocket: - GitHub - yonycalsin/nextjs-cors: nextjs-cors is a nod...
Zepeto
Zepetoβ€’15mo ago
I can't use native proxy of Nextjs ?
π›ˆπž‚π—Ώπžˆπ’†π’ˆπ–π°π›ˆ 𝐜0πŸƒ3𝗿
The native proxy feature of Next.js does not handle CORS headers automatically. @Zepeto But you can try setting it up in next config:
module.exports = {
async rewrites() {
return [
{
source: "/api/:path*",
destination: "https://api.example.com/:path*",
},
];
},
};
module.exports = {
async rewrites() {
return [
{
source: "/api/:path*",
destination: "https://api.example.com/:path*",
},
];
},
};
Zepeto
Zepetoβ€’15mo ago
it's finally working but not locally ahahah I have to deploy it on Vercel to see real result, it looks like http requests are subject to a CloudFlare test
Zepeto
Zepetoβ€’15mo ago
So I have to add this package to my app ? I don't have CORS problemes anymore
Zepeto
Zepetoβ€’15mo ago
I now have a certificate problem, I'm just looking for a way to be in https locally so I don't have to deploy each time the app on vercel to test it
Zepeto
Zepetoβ€’15mo ago
yes
π›ˆπž‚π—Ώπžˆπ’†π’ˆπ–π°π›ˆ 𝐜0πŸƒ3𝗿
Here's how to set up a self-signed SSL certificate for your Next.js app: - Install the mkcert utility by following the instructions in the mkcert README. mkcert is a utility that allows you to create self-signed SSL certificates. - Run mkcert -install to install the local CA (Certificate Authority) that mkcert uses to sign certificates. - In your Next.js project directory, run the following command to create a self-signed SSL certificate: mkcert -key-file key.pem -cert-file cert.pem localhost 127.0.0.1 ::1 This will create a private key file (key.pem) and a certificate file (cert.pem) in your project directory. The certificate is signed by the local CA installed in step Update your Next.js server configuration to use the SSL certificate. You can do this by adding the following code to your next.config.js file:
module.exports = {
serverOptions: {
key: fs.readFileSync(path.resolve(__dirname, 'key.pem')),
cert: fs.readFileSync(path.resolve(__dirname, 'cert.pem')),
},
};
module.exports = {
serverOptions: {
key: fs.readFileSync(path.resolve(__dirname, 'key.pem')),
cert: fs.readFileSync(path.resolve(__dirname, 'cert.pem')),
},
};
π›ˆπž‚π—Ώπžˆπ’†π’ˆπ–π°π›ˆ 𝐜0πŸƒ3𝗿
GitHub
GitHub - FiloSottile/mkcert: A simple zero-config tool to make loca...
A simple zero-config tool to make locally trusted development certificates with any names you'd like. - GitHub - FiloSottile/mkcert: A simple zero-config tool to make locally trusted develo...
Zepeto
Zepetoβ€’15mo ago
I got this error when I start the app ReferenceError: fs is not defined
π›ˆπž‚π—Ώπžˆπ’†π’ˆπ–π°π›ˆ 𝐜0πŸƒ3𝗿
Fs is a serverside Node.js package, are you calling it inside your client code?
Zepeto
Zepetoβ€’15mo ago
nop I just copied the module export
π›ˆπž‚π—Ώπžˆπ’†π’ˆπ–π°π›ˆ 𝐜0πŸƒ3𝗿
Here's an example of how to use the fs module in your next.config.js file: Install the fs-extra package by running npm install fs-extra or yarn add fs-extra. In your next.config.js file, import the fs-extra package and use it to read the SSL certificate files:

const fs = require('fs-extra');
const path = require('path');

const key = fs.readFileSync(path.resolve(__dirname, 'key.pem'));
const cert = fs.readFileSync(path.resolve(__dirname, 'cert.pem'));

const fs = require('fs-extra');
const path = require('path');

const key = fs.readFileSync(path.resolve(__dirname, 'key.pem'));
const cert = fs.readFileSync(path.resolve(__dirname, 'cert.pem'));
Make sure to adjust the path to the certificate files based on your project structure. Use the webpack property to customize the Next.js webpack configuration:
module.exports = {
webpack: (config, { isServer }) => {
// Add a custom plugin or loader that allows you to use the `fs` module
if (isServer) {
config.module.rules.push({
test: /\.(txt)$/i,
use: [
{
loader: 'file-loader',
options: {
publicPath: '/_next/static/files',
outputPath: 'static/files',
},
},
],
});
}

return config;
},
// Use the SSL certificate in your server options
serverOptions: {
key,
cert,
},
};
module.exports = {
webpack: (config, { isServer }) => {
// Add a custom plugin or loader that allows you to use the `fs` module
if (isServer) {
config.module.rules.push({
test: /\.(txt)$/i,
use: [
{
loader: 'file-loader',
options: {
publicPath: '/_next/static/files',
outputPath: 'static/files',
},
},
],
});
}

return config;
},
// Use the SSL certificate in your server options
serverOptions: {
key,
cert,
},
};
Zepeto
Zepetoβ€’15mo ago
You sure about that ?
π›ˆπž‚π—Ώπžˆπ’†π’ˆπ–π°π›ˆ 𝐜0πŸƒ3𝗿
I haven't personally tested the code, but it should work
Zepeto
Zepetoβ€’15mo ago
error - Failed to load next.config.js
Zepeto
Zepetoβ€’15mo ago
I just copied what you gave me
π›ˆπž‚π—Ώπžˆπ’†π’ˆπ–π°π›ˆ 𝐜0πŸƒ3𝗿
Check there isn't any red squigglies or errors in your editor
Zepeto
Zepetoβ€’15mo ago
Nothing in editor
Zepeto
Zepetoβ€’15mo ago
nop just added to it but it was almost empty
π›ˆπž‚π—Ώπžˆπ’†π’ˆπ–π°π›ˆ 𝐜0πŸƒ3𝗿
hmmm, might require some debugging to fix, but if I were you I'd consider if you could just use http instead of https locally
Zepeto
Zepetoβ€’15mo ago
Yes but the api blocks the request with cloudflare
Want results from more Discord servers?
Add your server
More Posts
infer parameters of function passed as prop on a react componentis there any way to infer the parameters values of a function passed with props? I am trying to crDoes cache control header work out of the box on self hosted NextJS APIs?Does the ``` "Cache-Control": "s-maxage=123123123" ``` work out of the box with self hosted NextJLooking for advice on how to fetch/load an onboarding bannerI'm using T3 inside a monorepo (turbo repo). For new users, I have a Get Started page that has a hanStack for Discord Bot + WebinterfaceHello! I am new to the t3-app stack and was wondering how to properly implement a service like discStripe webhook errorNext 12: I've followed Next official guide for integrating stripe into my published site on vercel, `onSuccess` is typed correctly as `data: ReturnItem` for one mutation but as `data: any` for another`onSuccess` is typed correctly as `data: ReturnItem` for one mutation but as `data: any` for anotherGoogle Provider when deployingI'm trying to deploy my project on vercel with a custom domain, but I'm getting an error that says sA Complex Union TypeHow to get this union type: ```js type MyType = "x:a" | "x:b" | "x:c" | "y:d" | "y:f" | "y:g"; ``` How do headless-ui expose context variable for child components?Hey I'm trying to recreate a similar pattern to what is used in `headless-ui` Menu components. httpsIs there something like tailwind ui / headless ui for react native?I'm a big fan of tailwindcss, but in order to speed up my process even more, I like to use something