Another CORS topic, it’s impresive how many are…
The context:
- NextJS app
- An API defined in the same NextJS app ( pages/api )
- URL: https://jmarroyave-dev.netlify.app
- next.config.js
const { i18n } = require('./next-i18next.config')
const configuration = {
pageExtensions: ['page.js', 'route.js'],
webpack: (config, { isServer }) => {
config.module = {
...config.module,
exprContextCritical: false,
};
if (!isServer) {
config.resolve.fallback = {
buffer: false,
fs: false,
process: false,
util: false,
assert: false,
};
}
config.resolve.symlinks = false
return config;
},
serverRuntimeConfig: {
PROJECT_ROOT: __dirname
},
distDir: 'build',
basePath: process.env.NEXT_PUBLIC__BASE_PATH,
i18n: i18n,
experimental: {
appDir: false,
},
reactStrictMode: true,
}
module.exports = configuration
The problem:
- when I try to fetch and API endpoint ( /api/post > src/pages/api/post.route.js ) from the client ( / > src/pages/index.page.js ) gets a CORS error
[Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at...]
on Localhost:
when I test this on localhost, the response header returns
"access-control-allow-origin : *"
but it’s missing when I test it on netlify
What I’ve tried:
- _headers file, inside the root directory and then inside the root/public
/*
Access-Control-Allow-Origin: *
- netlify.toml
[[headers]]
for = "/*"
[headers.values]
Access-Control-Allow-Origin = "*"
- setting the header in the route /root/pages/api/
import { createRouter } from "next-connect";
import cors from "cors";
const router = createRouter();
router
.use(cors())
.get( async(req, res) => {
const resp = await getData(req);
return res.json(resp);
})
export default router.handler({
onError(err, req, res) {
res.status(500).json({
error: (err).message,
});
},
})
async function getData(req) {
return { data: "some data"}
}
and with this (netlify instant answers)
export default async (req, ctx) => {
let res = ctx.json( await getData(req) )
res.headers.append('Allow-Access-Control-Origin', '*')
return res
}
async function getData(req) {
return { data: "some data"}
}
// this produces an error: Error [ERR_STREAM_WRITE_AFTER_END]: write after end
Logs
If the request was called from the SSR all the logs are shown on the Function Next.js SSR handler System but when are called from the ClientSide they don’t even log here
Questions
- Are the api/endpoints accesible to the internet?
Yes, they are available
https://jmarroyave-dev.netlify.app/api/blog
https://jmarroyave-dev.netlify.app/api/post?id=03-4-uncompleted-tasks
- Where are those requests logged?
Thanks for the help.
JM