I have set up a custom server in NextJS as illustrated here for custom routing.
server.js:
app.prepare()
.then(() => {
createServer((req, res) => {
const parsedUrl = parse(req.url, true)
const { pathname, query } = parsedUrl
if (foreignLang(pathname, lang)) {
app.render(req, res, checkLangAndConvert(links, pageVal, pathname, lang), query)
} else {
handle(req, res, parsedUrl)
}
})
.listen(port, (err) => {
if (err) throw err
console.log(`> Ready on http://localhost:${port}`)
})
})
it basically maps /en/url
to /another_url
for i18n.
I understand I can use query
parameter here and read it in the component, but I would like to pass options to the App
without rechecking the URL. Is it possible to pass options from server level to app level without reading the URL?
Edit: After a bit of investigating the marked answer explained that query
actually does not mean query-paramter in the URL, rather than passing a value from the server to client. Misleading word as it indicates only client side action. This was exactly what I needed.
Here is an example of custom-server-express where they pass id
from server to client side
So in your case it will be something like this
server.js
const { createServer } = require('http');
const { parse } = require('url');
const next = require('next');
const port = parseInt(process.env.PORT, 10) || 3000;
const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handle = app.getRequestHandler();
app.prepare().then(() => {
createServer((req, res) => {
const parsedUrl = parse(req.url, true);
const { pathname, query } = parsedUrl;
if (pathname === '/pl/index') {
app.render(req, res, '/index', { ...query, lang: 'pl' });
} else if (pathname === '/en/index') {
app.render(req, res, '/index', { ...query, lang: 'en' });
} else {
handle(req, res, parsedUrl);
}
}).listen(port, err => {
if (err) throw err;
console.log(`> Ready on http://localhost:${port}`);
});
});
pages/index.js
import React from 'react';
import { withRouter } from 'next/router';
function IndexPage(props) {
return <h1>index lang: {props.router.query.lang}</h1>;
}
export default withRouter(IndexPage);
Going to /pl/index
will render index lang: pl
and
going to /en/index
will render index lang: en
accordingly
Hope this helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With