Created
November 27, 2025 10:14
-
-
Save saviour123/792b3bed80b9eadb0b1710bfe64017b0 to your computer and use it in GitHub Desktop.
nextjs-custom-server.js is a patch for urlencode problem on cloudrun.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const { createServer } = require('http') | |
| const { parse } = require('url') | |
| const next = require('next') | |
| const dev = process.env.NODE_ENV !== 'production' | |
| const hostname = '0.0.0.0' | |
| const port = process.env.PORT || 8000 | |
| // Initialize Next.js app | |
| const app = next({ dev, hostname, port }) | |
| const handle = app.getRequestHandler() | |
| app.prepare().then(() => { | |
| createServer(async (req, res) => { | |
| try { | |
| // Parse the URL | |
| const parsedUrl = parse(req.url, true) | |
| let { pathname } = parsedUrl | |
| // Fix for Cloud Run encoded characters in static files | |
| // Cloud Run/GFE passes encoded URLs (e.g. %5BcountryCode%5D) which Next.js static handler doesn't decode automatically | |
| if (pathname && pathname.startsWith('/_next/static/')) { | |
| try { | |
| // Decode the entire pathname to handle %5B, %5D, %40 etc. | |
| const decodedPath = decodeURIComponent(pathname) | |
| if (decodedPath !== pathname) { | |
| // Update the parsedUrl object with the decoded path | |
| parsedUrl.pathname = decodedPath | |
| parsedUrl.path = parsedUrl.path.replace(pathname, decodedPath) | |
| parsedUrl.href = parsedUrl.href.replace(pathname, decodedPath) | |
| console.log(`> Rewrote encoded path: ${pathname} -> ${decodedPath}`) | |
| } | |
| } catch (e) { | |
| console.error('Failed to decode pathname', e) | |
| } | |
| } | |
| await handle(req, res, parsedUrl) | |
| } catch (err) { | |
| console.error('Error occurred handling', req.url, err) | |
| res.statusCode = 500 | |
| res.end('internal server error') | |
| } | |
| }) | |
| .once('error', (err) => { | |
| console.error(err) | |
| process.exit(1) | |
| }) | |
| .listen(port, () => { | |
| console.log(`> Ready on http://${hostname}:${port}`) | |
| }) | |
| }) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment