简体   繁体   中英

Fastify giving a react prop to a render with next.js

I am using Next.js's example server with Fastify and experimenting with it and am wondering if there is a way to pass let's say a JSON object as a prop into a render? I've tried to find anything in the documentation and can't find anything for doing this.

The server code I'm using is this,

const fastify = require('fastify')();
const Next = require('next');

const port = parseInt(process.env.PORT, 10) || 3000;
const dev = process.env.NODE_ENV !== 'production';

fastify.register((fastify, opts, next) => {
    const app = Next({ dev })
    app.prepare().then(() => {

        fastify.get('/', (req, res) => {
            let object = {"hello": "world"}; // object I want to pass as a prop
            return app.render(req.req, res.res, '/index', req.query).then(() => {
                res.sent = true
            })
        })

        next()
    }).catch(err => next(err))
})

fastify.listen(port, err => {
    if (err) throw err
    console.log(`Ready on http://localhost:${port}`)
})

Your question is not specific to Fastify , but relevant for all server frameworks.

The basic idea is that req & res object are passed to Next's getInitialProps .

So you can put your data on them.

For example, express's Response object has locals attribute that is specific to this job.

So, in order to pass data attach it to req / res.

fastify.get('/', (req, res) => {
  const object = { hello: 'world' }; // object I want to pass as a prop
  res.res.myDataFromController = object;
  return app.render(req.req, res.res, '/index', req.query).then(() => {
    res.sent = true;
  });
});
// some next page.jsx

const IndexPage = ({ dataFromGetInitilProps }) => (
  <div> {JSON.stringify(dataFromGetInitilProps, null, 2)} </div>
);

IndexPage.getInitilProps = ctx => {
  const { res } = ctx;

  // res will be on the context only in server-side
  const dataFromGetInitilProps = res ? res.myDataFromController: null; 

  return {
    dataFromGetInitilProps: res.myDataFromController,
  };
};

export default IndexPage;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM