Comments (6)
My solution is to modify the findAndGetUrls method. I am using the ENV var named basedPath. It works nicely
next.config.js
module.exports = {
assetPrefix: envConfig.ASSET_PREFIX,
publicRuntimeConfig: {
basePath: envConfig.BASE_PATH,
},
}
server.js
...
const server = express();
const router = express.Router();
router.get('*', (req, res) => handle(req, res));
server.use(envConfig.BASE_PATH, router);
server.listen(envConfig.PORT, (err) => {
if (err) throw err;
console.log(`> Ready on http://localhost:${envConfig.PORT}`);
});
...
routes.js
const escapeRegExp = require('lodash/escapeRegExp');
const config = require('next/config').default();
const routes = require('next-routes')();
const oldFindAndGetUrls = routes.findAndGetUrls.bind(routes);
routes.findAndGetUrls = (nameOrUrl, params) => {
const { basePath } = config.publicRuntimeConfig;
let mNameOrUrl = nameOrUrl;
if (basePath && basePath !== '/') {
const re = new RegExp(`^${escapeRegExp(basePath)}`);
mNameOrUrl = nameOrUrl.replace(re, '');
}
const findAndGetUrls = oldFindAndGetUrls(mNameOrUrl, params);
if (basePath && basePath !== '/') {
findAndGetUrls.urls.as = `${basePath}${findAndGetUrls.urls.as}`;
}
return findAndGetUrls;
};
// usage: routes.add(name, pattern, page);
routes
.add('index', '/', 'index')
.add('login', '/login', 'login');
module.exports = routes;
from next-routes.
I wanted to have all my routes prefixed with assetPrefix, but I didn't manage to export it from the config file in a clean way.
My solution was to replicate assetPrefix
in the public settings and override Link
with it:
next.config.js
const PREFIX = '/myAppPrefix'
module.exports = {
assetPrefix: PREFIX,
publicRuntimeConfig: {
assetPrefix: PREFIX,
},
}
routes.js
const { mapProps } = require('recompose')
const NextLink = require('next/link').default
const config = require('next/config').default()
const mapper = ({ as, href, ...props }) => {
const { assetPrefix } = config.publicRuntimeConfig
return {
...props,
as: `${assetPrefix}${as}`,
href: `${assetPrefix}${href}`,
}
}
const Link = mapProps(mapper)(NextLink)
const routes = (module.exports = require('next-routes')({ Link }))
routes.add('home', '/', 'index')
...
from next-routes.
Hi @fridays!
Thanks for quick replying.
My solution is just exactly like you & I added some changes to it.
nextjs: ver 2.1.1
routes.js
const nextRoutes = require('next-routes');
const routes = module.exports = nextRoutes();
routes.add('index', '/prefix/:area');
server.js
const routes = require('./routes')
const handle = routes.getRequestHandler(app)
app.prepare().then(() => {
const server = express();
// create router from express
const router = express.Router();
// this will prevent 404 not found when copy & parse url in browser's address bar
router.get('/:area', (req, res) => {
return app.render(req, res, '/index', req.query);
});
router.get('*', (req, res) => {
handle(req, res);
});
// bind prefix to resource url
server.use('/prefix', router);
server.use('/prefix/static', express.static('static'));
server.use(handle);
server.listen(3000, err => {
if (err)
throw err;
console.log(`> Ready on http://localhost:3000/prefix`);
});
});
_document.js
Because I use prefix so that I have to modified _document.js
to override <NextScript />
component to serve resource with prefix like this: vercel/next.js#257 (comment)
from next-routes.
@davidnguyen179 @fridays
it's working,but how about a route scope like express router
scope = routes.addScope("/prefix")
scope.add(somename, "/user") // ===> "/prefix/user"
from next-routes.
I'm using Next 5.0 which supports "zones" and asset prefixes. I was running into an issue where next-routes was not working well with 5.0's prefixes.
In case someone else has this issue, here is my hack until something better comes along:
const routes = require('next-routes')();
routes
.add('postsPrefix', '/prefix/posts/:id?', 'posts')
.add('posts', '/posts/:id?', 'posts'); // both have to exist
module.exports = routes;
Then to go to a prefixed page supported by next-routes:
Router.pushRoute('postsPrefix', { id });
from next-routes.
I think you can't globally prefix a Next.js app like it's /static
or /_next
folders.
But you could do this in routes.js:
routes.add('index', '/prefix/:area')
And in server.js:
const routes = require('./routes')
const handle = routes.getRequestHandler(app)
app.prepare().then(() => {
const server = express();
server.use('/prefix/static', express.static('static'));
server.use(handle);
server.listen(3000, err => {
if (err)
throw err;
console.log(`> Ready on http://localhost:3000/prefix`);
});
});
from next-routes.
Related Issues (20)
- Click on link and URL update is not working HOT 1
- Complex { Link } from routes module doesn't work when coming from static pages, but does when navigated to first HOT 5
- next 9 with next-routes and public folder not working
- Route pushRouter makes app refresh
- Empty value for route
- Nextjs v9 - Parameter 'url' must be a string, not undefined HOT 1
- Is this library alive? HOT 22
- Refresh results in 404 page not found HOT 4
- Bug with getServerSideProps HOT 2
- Compatibility with getStaticPaths HOT 1
- Error using Link component "Warning: Function components cannot be given refs." HOT 1
- Failed to decode downloaded font
- slugs are not working with dynamic routes after upgrading to next 9.5 HOT 2
- assigning the index page to multiple routes leads to infinite reloading HOT 1
- Page Both Accessible From Route Url And NextPage Name HOT 1
- Next 10 HOT 2
- React 17.02, next js 11 HOT 2
- Migrating from next-routes to built-in Next.js routing? HOT 1
- vercel deployment with this lib
- Migration steps for nextjs inbuilt routing HOT 1
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from next-routes.