Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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.

like image 606
supersize Avatar asked Oct 04 '18 08:10

supersize


1 Answers

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!

like image 180
iurii Avatar answered Nov 03 '22 02:11

iurii