-
Notifications
You must be signed in to change notification settings - Fork 27k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Multiple Next apps on single domain will collide #257
Comments
I believe I opened an issue for mounting, or I should have otherwise. The idea is that you'll be able to supply a prefix in the next config (like |
There are a few caveats however. For example, cc @nkzawa |
Configurable prefixes would work perfectly for our use case. |
The problem of For example, when there are two apps which mounted to |
Another option is a compile-time thing.
and we can replace it with webpack |
Another options is to fetch the value on
// response
{
"component": "...",
"pathPrefix": "/b"
} Maybe we can detect if it's an external component by comparing to own |
Cannot waiting this option. Now I extends Client side I monkey path |
We won't be implementing it in the short term. If anyone wants to work on it, we could certainly provide feedback on suggested designs |
Maybe by using the |
@cncolder Do you have a gist or something illustrating your overrides? |
@JohnPhoto, these are the monkey-patches we've done to support this. It assumes that _document only gets rendered on the server. In
Hope this helps. |
Above solution is not working in version 2.1.1 Here is the replacement which working in import Document, { Head, Main, NextScript } from 'next/document';
class PrefixedNextScript extends NextScript {
render() {
const { __NEXT_DATA__ } = this.context._documentProps;
const { prefix } = this.props;
const env = process.env.NODE_ENV;
// script element contain development js
let scriptElements = (
<div>
<script type="text/javascript" src={`${prefix}/_next/-/manifest.js`} />
<script type="text/javascript" src={`${prefix}/_next/-/commons.js`} />
<script type="text/javascript" src={`${prefix}/_next/-/main.js`} />
</div>
);
if (env === 'production') {
const { buildStats } = __NEXT_DATA__;
const app = 'app.js';
// script element contain production js
scriptElements =
<script
type="text/javascript"
src={`${prefix}/_next/${buildStats[app].hash}/${app}`}
/>
}
return (
<div>
<script
dangerouslySetInnerHTML={
{ __html: `__NEXT_DATA__ = ${htmlescape(__NEXT_DATA__)}; module={};` }
}
/>
{scriptElements}
</div>
);
}
} Here is how to use it <PrefixedNextScript prefix={config.prefixResource} /> this script will replace <NextScript /> in _document.js |
This issue should be close, |
@tpai does the assetPrefix fix this issue. |
Hi @arunoda.
For example, when run command to build in production mode. The |
@nndung179 @arunoda Not perfectly fixed, but it still work. next.config.js module.exports = {
assetPrefix: '/prefix/'
}; customServer.js express.use((req, res) => {
req.url = req.url.replace('/prefix', '');
handle(req, res);
}); |
I had a PR to fix this on the frontend side as well so you wouldn't need custom server logic for this: |
That's indeed a big issue. Since Next.js is provided as a provided as a public framework for hosting server rendered React pages in an easy way, it should be possible also to host the solution on a subdomain. We decided to use Next.js for our next admin-webapp, but this will be hosted under a subdomain like www.some-domain.com/admin and this would actually not possible or am I wrong? |
@janbaer it actually possible. I have met the same problem like you. I used the solution above to solve. But I believe in the future it will be solved |
If anyone else is trying to run next on a sub-route with express, I had to use this express route to re-write the HMR pings:
|
Thanks for that solution @wesbos 👌 Pretty sure it'll help people 👍 |
@nndung179 @wesbos Thanks for your solutions, I'll try it. But I think it should be a feature of the framework, like the feature with for the CDN support. |
I tried to use the server side solutions from @wesbos and @tpai and it worked for me locally somehow. But in case it would run on a server with Nginx as proxy-server which is only the /admin requests proxy to my Next.js page it wouldn't work, since the request to /_next wouldn't arrive in my server.js. |
The multi-zones branch is 404ing 😞 https://github.com/zeit/next.js/tree/multi-zones |
@timneutkens It looks like the multi-zones branch was merged, since there's now a Multi Zones section in the README? Is this issue resolved? /cc @moaxaca |
Hi @zenflow, yep it was merged and released in 5.0.0. |
Yep this should be closed 🎉 |
I used: In my // ---- API Routes ----
const express = require('express')
const router = express.Router()
// -------- NextJs API Routes --------
router.get(`*`, (req, res, next) => {
return app.getRequestHandler() // where app is nextjs app object
})
module.exports = router In my const server = require('express')()
let routes = require('routes.js')
server.use('/my_custom_base_url', routes)
server.listen(port, (error) => { // Start server to listen on specified port
if (error) throw error
console.log('Server started.')
}) and in my module.exports = {
assetPrefix: '/my_custom_base_url'
publicRuntimeConfig: {
staticFolder: `/my_custom_base_url/static`
},
webpack: (config) => {
// Fixes npm packages that depend on `fs` module
config.node = {
fs: 'empty'
}
return config
}
} This fixed all of my routing issues and will make the base url of the entire nextjs webapp to have a base url of '/my_custom_base_url' My version of NextJs is Hope this helps! I have also mentioned this as a solution to Issue #2901 |
For anyone being redirected to this issue ticket trying to just get next mounting to a subdirectory (such as from #2452), here's what finally ended up working for me.
// We can use middleware to rewrite the url so next handles it as if it wasn't in a subdirectory i.e.
I have not thoroughly tested yet, but this worked when deployed as well. For my use case, I have only one next.js app and it is merely accessible via /my_custom_base_url. Due to service routing, requests above /my_custom_base_url/ (i.e. /_next/) are not intercepted at all by the next service. Hope this helps save someone else an afternoon of head scratching. |
Hey, I'm currently facing the same problem where I have a basePath and need to have the site working on http://domain/basePath I've tried both solutions above but it doesn't seem to be working. Without the basePath it works fine, but with it I still get a 404 page not found. Any ideas what I could be missing? Below is my server.js
|
Hey I have a similiar situation with basePath, but can't get out of it. I have tried my own solution at first, but when it didn't work 100% I used @bgarrett-rt 's code for the server.
const express = require('express');
const compression = require('compression');
const next = require('next');
const { config } = require('./env-config');
const dev = config['NODE_ENV'] !== 'production';
const PORT = config['PORT'] || (dev ? 4100 : 80);
const ROOT_PATH = config['ROOT_PATH'] || '/';
const app = next({ dev });
const handle = app.getRequestHandler();
app.prepare().then(() => {
const server = express();
server.use(compression());
server.use((req, res, next) => {
req.url = dev ? req.originalUrl :
req.originalUrl.replace(ROOT_PATH, '');
next();
})
server.get('*', (req, res) =>
handle(req, res));
server.listen(PORT, err => {
if (err) throw err;
//eslint-disable-next-line
console.log(`> Ready on http://localhost:${PORT}`);
});
});
const withPlugins = require('next-compose-plugins');
const sass = require('@zeit/next-sass');
const css = require('@zeit/next-css');
const fonts = require('next-fonts');
const images = require('next-images');
const { config } = require('./env-config');
const dev = config['NODE_ENV'] !== 'production';
const rootPath = dev ? '' : config['ROOT_PATH'];
module.exports = withPlugins([
[sass], [css], [fonts], [images]
], {
publicRuntimeConfig: {
rootPath
},
assetPrefix: rootPath
}); The initial load works fine - no 404's whatsoever, but after clicking any link it just loads the page infinitely. While watching the requests, all the needed chunks are loaded succesfully, it just looks like if after loading of the chunks something goes wrong and the page isn't being rendered. I guess that it is also worth noting that i'm using the Can someone point me in some kind of direction? I'm banging my head at this for half a day now... |
First time experience with next.js, was disappointed that building + copying to personal web directory didn't work out of the box. For anyone googling this in the future, I'll leave a note to hopefully save them the hour I spent trying to google this. To get a quick "see what next.js means by deployment" view, you must create a
then you can make the setup example and run
which will allow you to see something at This doesn't solve the larger issue(s) raised in this thread, but at least will allow a newcomer to see what next.js calls a "production build." Note that unlike CRA next.js requires both a build and an export step; 'build' here doesn't build anything that could be deployed. The main documentation doesn't mention this step directly, but the extra step of setting assetPrefix is hidden in a page titled Deploying a Next.js app into GitHub Pages linked from there for people wanting to deploy on github pages. I would be kind of nice if the default setup didn't assume domain root access and used relative paths only, but perhaps I'm stuck in the 1990s and in any event would apply only to 100% static applications which next.js perhaps doesn't target. |
When I deploy to server, then the states in redux be lost after change page. How to fix it? @wesbos |
Had a hard time figuring this out initially. Wrote a blog post on the solution https://www.alexhughes.dev/blog/multiple-next-apps/ |
Were you able to make any progress on this? I seem to be experiencing the exact same issue. I'm re-writing my urls the same way you are so I can use a |
Hi all, whoever is facing this problem this below solution has worked absolutely spot-on for me in a non Now environment. This guides you to achieve Zones like capability that Zeit Now provides. One improvement i did, was to create a routes.js file which just returns an object of routes, so that i don't have to create wrapper components to prepend base path prefix. |
Does hot-loading work in development mode? And do Link components work? |
Yes, hot reloading works as usual. As far as Link component is concerned, you should write a wrapper that adds base_path to all your links. This blog I referenced has example for it. |
@vinodloha |
Next.js 9.5 was just released with support for a Customizable Base Path, allowing you to mount multiple Next.js apps on one domain, so long as their subpaths are unique! |
@Timer if you want to change only the prefix/path of the static files? |
@Timer @timneutkens , as the original request says, we have multiple next apps running on the same domain. When we use base path and use proxy passes to handle which request should go to which Next app most of the things work. The one problem that we aren't able to mitigate is to keep links 'clean'. Say our basepath is The way we tried to solve this was to manually have rewrites for assets, images and api routes, something like this: {
assetPrefix: 'app-1',
async rewrites() {
return [
/* for assets */
{
source: `/app-1/_next/:path*`,
destination: '/_next/:path*',
},
/* for images */
{
source: `/app-1/images/:query*`,
destination: '/_next/image/:query*',
},
{
/* for api routes */
source: `/app-1/api/:path*`,
destination: '/api/:path*',
},
]
},
} This way our original links remain as is. But the problem with this is that we have no way to write a re write rule for One solution I'm trying to think of is to catch these api calls in service worker, re route them to Last resort is to use custom server, but we are trying to find if there's a workaround or solution without doing that, since some of our pages use |
We ended up using |
This issue has been automatically locked due to no recent activity. If you are running into a similar issue, please create a new issue with the steps to reproduce. Thank you. |
Next uses routes like
/_next
and/static
by default. If you wanted to run multiple different Next apps on the same domain, they would collide with each other. Can these paths be made configurable?The text was updated successfully, but these errors were encountered: