You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I am running into this issue, where the Access-Control-Allow-Origin header is missing from the /_vercel/insights/view endpoint when reverse proxying (so it works when I am on the request URL directly but not when there's a referrer url. I have added the headers to the vercel.json, the next.config.js, the middleware that handles it, and even tried on the proxy's side via Cloudflare. Hoping to get some help in solving this, and share as much context as I can
constpath=require('path')const{ withSentryConfig }=require('@sentry/nextjs')const{ version }=require('./package.json')/** @type {import('next').NextConfig} */constnextConfig={assetPrefix: process.env.ASSET_PREFIX??'',compiler: {styledComponents: true,},reactStrictMode: false,images: {domains: ['asset-url','another-asset-url'],loader: 'custom',loaderFile: './src/imageLoader.js',formats: ['image/avif','image/webp'],},webpack: (config,options)=>{const{ dev, isServer }=optionsconfig.resolve.alias['styled-components']=path.resolve('./node_modules/styled-components')returnconfig},logging: {fetches: {fullUrl: true,},level: 'verbose',},modularizeImports: {lodash: {transform: 'lodash/{{member}}',},},experimental: {forceSwcTransforms: true,instrumentationHook: true,},env: {VERSION: version,},asyncheaders(){return[{source: '/(.*)',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',},],},]},}module.exports=withSentryConfig(// withBundleAnalyzer(nextConfig),nextConfig,{// For all available options, see:// https://github.com/getsentry/sentry-webpack-plugin#options// Suppresses source map uploading logs during buildsilent: true,org: 'my-org',project: 'my-project',},{// For all available options, see:// https://docs.sentry.io/platforms/javascript/guides/nextjs/manual-setup/// Upload a larger set of source maps for prettier stack traces (increases build time)widenClientFileUpload: true,// Transpiles SDK to be compatible with IE11 (increases bundle size)transpileClientSDK: false,// // Routes browser requests to Sentry through a Next.js rewrite to circumvent ad-blockers. (increases server load)// // Note: Check that the configured route will not match with your Next.js middleware, otherwise reporting of client-// // side errors will fail.// tunnelRoute: '/monitoring',// Hides source maps from generated client bundleshideSourceMaps: true,// Automatically tree-shake Sentry logger statements to reduce bundle sizedisableLogger: true,environment: process.env.VERCEL_ENV,// Enables automatic instrumentation of Vercel Cron Monitors.// See the following for more information:// https://docs.sentry.io/product/crons/// https://vercel.com/docs/cron-jobsautomaticVercelMonitors: true,})
The middleware
import{NextResponse,NextRequest}from'next/server'import{addQueryStringParams,join,getFullIDUrl}from'./api/ssr/utils'import{OrderAttribution}from'shared'import{notFound}from'next/navigation'import{logMiddlewareError}from'./utils/sentry'constPROXY_TYPE_ID='myorg-type-id'constPROXY_TYPE_ID_OLD='myorg-id'constPROXY_TYPE_PATH='myorg-exampleB-path'constPROTOCOL=process.env.NEXT_PUBLIC_ENV==='local' ? 'http' : 'https'exportasyncfunctionmiddleware(request: NextRequest){constresponse=NextResponse.next()if(request.method==='HEAD'){console.log('HEAD request, returning 200 request',request)console.log('HEAD request, returning 200 response',NextResponse.json({},{status: 200}))returnNextResponse.json({},{status: 200})}// NOTE: here I have tried adding these headers as both the request headers and the response headers to no avail.request.headers.set('Access-Control-Allow-Origin','*')request.headers.set('Access-Control-Allow-Credentials','true')request.headers.set('Access-Control-Allow-Methods','GET,OPTIONS,PATCH,DELETE,POST,PUT')request.headers.set('Access-Control-Allow-Headers','X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version')if(request.method!=='GET'){returnresponse}constrequestUrl=newURL(request.nextUrl)constnextUrl=request.nextUrl.clone()try{constrequestHeaders=newHeaders(request.headers)constid=requestHeaders.get(PROXY_TYPE_ID)??requestHeaders.get(PROXY_TYPE_ID_OLD)letstorePath=requestHeaders.get(PROXY_TYPE_PATH)typePath=typePath?.startsWith('/') ? typePath : `/${typePath}`constnextJsUrl=request.nextUrl.toString()requestHeaders.set('x-pathname',request.nextUrl.pathname)requestHeaders.set('x-url',nextJsUrl)constnextUrlSearchParams=nextUrl.searchParamsaddRequestHeaders({
nextUrl,searchParams: nextUrlSearchParams,
requestHeaders,})// ---- proxying ----//if we have an id and an external path, we are being proxied to.//so we need to rewrite the url to the correct path.//the incoming url will be something like '/place/type/things'.//we need to rewrite it to '/:id/stuff/things':// -- the 'myorg-type-id' is set by the customer's proxy// to tell us which store we are on, used to replace ${id} below// -- the 'myorg-type-path' is set by the customer's proxy// to tell us which part of the url our stuff should come after//ex. '/place/type'//we replace that with the id and '/endpoint' which matches the folder structure for NextJS (src/app/[id]/endopint/thing.tsx).if(id&&typePath){console.log(`----- PROXYING id:${id} typePath:${typePath} -----`)if(nextUrl.pathname==='/robots.txt'){returnNextResponse.rewrite(newURL('/robots.txt',nextUrl))}constnewUrl=newURL(requestUrl.pathname.replace(path,''),`${PROTOCOL}://${requestUrl.hostname}:${requestUrl.port}`)if(nextUrl.pathname.endsWith('/robots.txt')){returnNextResponse.rewrite(newURL('/robots.txt',newUrl))}constdir=newUrl.pathname.startsWith('/exampleA') ? '' : 'exampleB'constrewritePathname=addQueryStringParams(join(`/${id}/${dir}`,newUrl.pathname),Object.fromEntries(nextUrlSearchParams.entries())??{})constrewriteUrl=newURL(rewritePathname,newUrl.toString())returnNextResponse.rewrite(rewriteUrl,{headers: requestHeaders,})}// console.log('----- NO PROXYING -----')if(nextUrl.pathname==='/our-endpoint'&&nextUrlSearchParams.get('id')){constnewUrl=newURL(request.url)constrewritePathname=addQueryStringParams(join(`/${nextUrlSearchParams.get('id')}`,nextUrl.pathname),Object.fromEntries(newUrl.searchParams.entries())??{})returnNextResponse.rewrite(newURL(rewritePathname,newUrl.toString()),{headers: requestHeaders,})}//ORG Iframe Connect Mode//ORG consumer apps should point to /{id}/org-connect?orgUid=12345&anAuthToken=4567if(nextUrl.pathname.match(/\/[0-9A-Z&\-%]*\/org-connect/i)){if(!nextUrlSearchParams.get('orgUid')||!nextUrlSearchParams.get('anAuthToken')){returnNextResponse.rewrite(newURL('/not-found',nextUrl.toString()),{headers: requestHeaders,})}requestHeaders.set('an-attribute, 'true') } return NextResponse.next({ request: { headers: requestHeaders, }, }) } catch (error) { logMiddlewareError(error, { url: requestUrl.pathname, }) return notFound() }}function addRequestHeaders({ nextUrl, searchParams, requestHeaders,}: { nextUrl: URL searchParams: URLSearchParams requestHeaders: Headers}) {......... requestHeaders.set( 'example-myorg',searchParams.get('example')??'')...}exportconstconfig={matcher: ['/((?!api|_vercel|_next/static|/monitoring|_next/image|favicon.ico|robots.txt|ads.txt|sitemap.xml|manifest.json|android-chrome-*.png|apple-touch-icon.png|browserconfig.xml|mstile-150x150.png|safari-pinned-tab.svg|site.webmanifest|favicon-.*.png).*)',],}
Then in Cloudflare, I tried from the org doing to proxy to set the headers following their docs, with no such luck.
In the browser, we see a CORs error with a missing header, and I do see it's missing but can't seem to add it with any of the above
I suspect there's some issue either with how we have Vercel Analytics implemented, or NextJS is stripping the header at some point, but have hit a bit of a wall and could use new eyes. Thanks in advance for any help!
The text was updated successfully, but these errors were encountered:
I am running into this issue, where the
Access-Control-Allow-Origin
header is missing from the/_vercel/insights/view
endpoint when reverse proxying (so it works when I am on the request URL directly but not when there's a referrer url. I have added the headers to thevercel.json
, thenext.config.js
, the middleware that handles it, and even tried on the proxy's side via Cloudflare. Hoping to get some help in solving this, and share as much context as I canThe
vercel.json
file:The
next.config.js
The middleware
How we set analytics:
Then in Cloudflare, I tried from the org doing to proxy to set the headers following their docs, with no such luck.
In the browser, we see a CORs error with a missing header, and I do see it's missing but can't seem to add it with any of the above
I suspect there's some issue either with how we have Vercel Analytics implemented, or NextJS is stripping the header at some point, but have hit a bit of a wall and could use new eyes. Thanks in advance for any help!
The text was updated successfully, but these errors were encountered: