How to pass arbitrary values into Nuxt (before it boots)

Viewed 83

I'm running Nuxt on Lambda, and starting it up like this:

const { loadNuxt } = require('nuxt-start');

module.exports.render = async (event) => {
  const nuxt = await loadNuxt({ for: 'start' });
  const { html } = await nuxt.renderRoute(event.requestContext.http.path);

  return {
    statusCode: 200,
    body: html,
    headers: {
      'Content-Type': 'text/html',
    },
  };
};

Within the Nuxt app, I need to access the user's IP address, but Nuxt's context.req object is missing (since Nuxt is not being loaded by a network request directly), so I'm not able to grab the user's IP address from there.

The Lambda event object does have it, however, in event.requestContext.http.sourceIp. Is there some way I can inject this value into the above load process so I can access it within Nuxt's asyncData() method?

1 Answers

Figured it out! Solution:

  const { html } = await nuxt.renderRoute(event.requestContext.http.path, {
    sourceIp: event.requestContext.http.sourceIp,
  });

And then the IP address is available within asyncData:

  async asyncData({ params, $axios, $cookies, error, ssrContext }) {
    console.log('IP:', ssrContext.sourceIp);
    // ...
Related