jakeburden / next-absolute-url

Get the absolute URL of your Next.js app (optionally set a localhost dev URL)
300 stars 30 forks source link

not compatible with getInitialProps ? #10

Closed andrewlorenz closed 4 years ago

andrewlorenz commented 4 years ago

I'm getting ReferenceError: window is not defined when I try to use this module in getInitialProps. I need to do a fetch for my context data, but I can't hard-code the url - hence looking to use next-absolute-url. But this is failing.

import fetch              from 'isomorphic-unfetch';
import absoluteUrl        from 'next-absolute-url';

export default class MyApp extends App {
  static async getInitialProps(ctx) {
    const { origin } = absoluteUrl(ctx.req);
    console.log('origin', origin);
  }
  render() {
    // etc
  }
}
andrewlorenz commented 4 years ago

... which is a bit weird considering this is exactly the use case that the codeconqueror blog article covers! I'm getting this error on the CLIENT not the SERVER too, so I'm totally scratching my head as to why the window object isn't available there. Its almost like my client is the server, and the server is the client !?

cronokirby commented 4 years ago

ctx is a named argument to getInitialProps, so you want:

static async getInitialProps({ ctx }) {
  const { origin } = absoluteUrl(ctx.req);
}

I just ran into this error myself hehe.

andrewlorenz commented 4 years ago

my my, you are right - many thanks! I'm not sure I would have ever spotted that - I guess its to do with the props cascade from Next's to this MyApp which extends it. But thank you muchly for spotting my ticket and giving me the fix.

jakeburden commented 4 years ago

Thanks @andrewlorenz and @cronokirby for pointing this out! I'll try to add the this to a docs update soon.

borispoehland commented 4 years ago

ctx is a named argument to getInitialProps, so you want:

static async getInitialProps({ ctx }) {
  const { origin } = absoluteUrl(ctx.req);
}

I just ran into this error myself hehe.

Actually no, ctx is no named argument of getInitialProps, see https://nextjs.org/docs/api-reference/data-fetching/getInitialProps

I just ran into the same error window is not defined. Any help is appreciated. I'm using it in App.getInitialProps

jakeburden commented 4 years ago

I think that's related to this bug, which I haven't gotten around to addressing yet: https://github.com/jekrb/next-absolute-url/issues/14, https://github.com/jekrb/next-absolute-url/issues/12

I'm actually not sure when I'll time to work on a fix. I'd happily accept a pull request if anyone wants to give it a try.

borispoehland commented 4 years ago

@jekrb my workaround is to use your function only in pages, not in _app.js, because there the window is defined. Maybe it's a framework limitation, that window is undefined in _app.js