Pass Variables From Custom Server To Components In Nextjs
I have set up a custom server in NextJS as illustrated here for custom routing. server.js: app.prepare() .then(() => { createServer((req, res) => { const parsedUr
Solution 1:
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' });
} elseif (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
importReactfrom'react';
import { withRouter } from'next/router';
functionIndexPage(props) {
return<h1>index lang: {props.router.query.lang}</h1>;
}
exportdefaultwithRouter(IndexPage);
Going to /pl/index
will render index lang: pl
and
going to /en/index
will render index lang: en
accordingly
Hope this helps!
Post a Comment for "Pass Variables From Custom Server To Components In Nextjs"