matthewmueller / next-cookies

Tiny little function for getting cookies on both client & server with next.js.
368 stars 17 forks source link

Cannot read property 'headers' of undefined #16

Closed andrew-oko-odion closed 5 years ago

andrew-oko-odion commented 5 years ago
export default class Me extends Component {
  static async getInitialProps (ctx) {
    const { token } = nextCookie(ctx)
  }

}

I get Cannot read property 'headers' of undefined


Possibly related to #15

andrew-oko-odion commented 5 years ago

Or am I not importing next-cookies the right way import nextCookie form 'next-cookies'

and on the server console I have this cookie set

{
  'rack.session': 'BAh7BkkiD3Nlc3Npb25faWQGOgZFVEkiRWY1YjU4NjVlMWU3NzdiNGQwNjBh\n' +
    'NWFhNWMzNzYzMGVmZDQwNDk4ZGQ0NGJmZTU2ZWFlYTQxN2UzOTE1ZTc1MTgG\n' +
    'OwBG\n--1c519244d56d2406e8239575f3253d5662b8e490',
  _session_id: '0Wz61EJzJrxQhAPR3oWD0hR+bV2N7aI/QWjRKtN4b07ii3bd3lv6iPvmpUwRYkxHh7c8xD9HEsuBPSdn3RLDqmZjFzzkfAZ0u6D6b3AuUJ6naOhU83/b0YHoSgLA6nDHOucsu2BgQTHSsfvhTcA6dBhNUKxeTV/GNOGjkD8Ho+4jgQKgDnSWgJjRqWVwwHdAqYVLJ9cMhvcSGmYMx/7efDqitmTLEgMYVOF2BovanWAZu6+GIHovbmNQAg==--yTFd1cYavkgQcpZB--DJAOuuw4Bj0UAQmNGHGbbg==',
  token: 'Bearer ' +
    'eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiI4Iiwic2NwIjoidXNlciIsImF1ZCI6bnVsbCwiaWF0IjoxNTYwNTQxODQ2LCJleHAiOjE1NjA1NDU0NDYsImp0aSI6ImQ4MjRiMWQ1LTUwY2MtNDMzZS05MjdhLTViNGFhZmQxN2RmMyJ9.oVWaKDuppUO3GXtxrWVBl0mk0fCQw_OB1OT3uphr7C4'
}
nfriedly commented 5 years ago

Can you check the version that's installed by running

npm ls next-cookies

And then also show me your code?

andrew-oko-odion commented 5 years ago

I am using "next-cookies": "1.1.2" && "next": "latest"

Also here is my code

import React from 'react';
import SignInForm from '../components/forms/SignInForm';
import fetch from 'isomorphic-unfetch';
import cookie from 'js-cookie';
import nextCookie from 'next-cookies';

class Login extends React.Component {

    static async getInitialProps(ctx) {
    const { token } = nextCookie(ctx)
    console.log(token);
     }

    constructor (props) {
    super(props)

    this.state = { email: '', error: '' }

    this.handleSubmit = this.handleSubmit.bind(this)
  }

    async handleSubmit (values) {
    console.log(values);
    this.setState({ error: '' });
    const email = this.state.email
    const url = 'http://localhost:3001/users/sign_in'

    try {
        const response = await fetch(url, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json',
               'Accept': 'application/json'
             },
        body: JSON.stringify({ user: {...values }})
        })
        if (response.ok) {
        console.log(response.headers.get('Authorization'));
        const token = response.headers.get('Authorization');
        // set cookie
        cookie.set('token', token);
        } else {
        console.log('Login failed.')
        let error = new Error(response.statusText)
        error.response = response
        throw error
        }
    } catch (error) {
        console.error(
        'You have an error in your code or there are Network issues.',
        error
        )
        this.setState({ error: error.message })
    }
    }

    render(){
    return (
        <React.Fragment>
        <SignInForm onSubmit={this.handleSubmit} />
        </React.Fragment> 
    )
    }
}

export default Login;

And Here is the error message on the browser

×
TypeError: Cannot read property 'headers' of undefined
Cookies
/home/niceguy/workspace/javascript/bustrio/node_modules/next-cookies/next-cookies.node.js:18:16
_callee$
./pages/login.js:10
   7 | class Login extends React.Component {
   8 | 
   9 |     static async getInitialProps(ctx) {
> 10 |  const { token } = nextCookie(ctx)
  11 |  // const { req } = ctx;
  12 |  // return { req } ;
  13 |  console.log(token);
View compiled
▶ 9 stack frames were collapsed.
_callee$
./pages/_app.js:16
  13 | let pageProps = {}
  14 | 
  15 | if (Component.getInitialProps) {
> 16 |     pageProps = await Component.getInitialProps({ ctx })
     | ^  17 | }
  18 | 
  19 | return { pageProps }
View compiled
▶ 3 stack frames were collapsed.
nfriedly commented 5 years ago

It looks like it's using the node.js version of next-cookies in the browser. Do you have a custom webpack config or anything like that?

Also can you give me the actual output of npm ls next-cookies && npm ls next ? It's possible to have a different version installed than what your package.json requests.

andrew-oko-odion commented 5 years ago

Here is the output of npm ls next-cookies && npm ls next

with-redux-saga@1.0.0 /home/niceguy/workspace/javascript/bustrio
└── next-cookies@1.1.2 

with-redux-saga@1.0.0 /home/niceguy/workspace/javascript/bustrio
└── next@8.1.0  invalid

Here is my next.config.js

const withLess = require('@zeit/next-less')
const lessToJS = require('less-vars-to-js')
const fs = require('fs')
const path = require('path')

module.exports = withLess({
  lessLoaderOptions: {
    javascriptEnabled: true,
  },
  webpack: (config, { isServer }) => {
    if (isServer) {
      const antStyles = /antd\/.*?\/style.*?/
      const origExternals = [...config.externals]
      config.externals = [
        (context, request, callback) => {
          if (request.match(antStyles)) return callback()
          if (typeof origExternals[0] === 'function') {
            origExternals[0](context, request, callback)
          } else {
            callback()
          }
        },
        ...(typeof origExternals[0] === 'function' ? [] : origExternals),
      ]

      config.module.rules.unshift({
        test: antStyles,
        use: 'null-loader',
      })
    }
    return config
  },
})
andrew-oko-odion commented 5 years ago

Eventually I had to bypass this package and used nexted destructuring to get my set cookies

    static async getInitialProps (props) {
    const { store, isServer, query, req: {cookies: {token} } } = props.ctx
    console.log(token);
    return {token}
    }
nfriedly commented 5 years ago

Oh, interesting. It looks like something else is already parsing the cookies. (And removing the headers?)

Are you using a custom server, by chance?

andrew-oko-odion commented 5 years ago

Yes I have an express server

On Thu, Jun 20, 2019 at 11:46 AM Nathan Friedly notifications@github.com wrote:

Oh, interesting. It looks like something else is already parsing the cookies. (And removing the headers?)

Are you using a custom server, by chance?

— You are receiving this because you authored the thread. Reply to this email directly, view it on GitHub https://github.com/matthewmueller/next-cookies/issues/16?email_source=notifications&email_token=ABACDMFJMTJQT3FZYTQNKM3P3NNZHA5CNFSM4HYOP27KYY3PNVWWK3TUL52HS4DFVREXG43VMVBW63LNMVXHJKTDN5WW2ZLOORPWSZGODYFBN4A#issuecomment-503977712, or mute the thread https://github.com/notifications/unsubscribe-auth/ABACDMB7O35YFJCGVUYGNSLP3NNZHANCNFSM4HYOP27A .

himadrinath commented 5 years ago

its working fine for me

sacmii commented 5 years ago

Screenshot 2019-10-03 at 7 51 50 PM Facing Issue: "next": "9.0.7", "next-cookies": "^1.1.3", And _app.js ` static async getInitialProps({ Component, ctx }) {

    let pageProps = {}
    if (Component.getInitialProps) {
        pageProps = await Component.getInitialProps({ ctx })
    }
    return { pageProps }

}

`

rohan-deshpande commented 5 years ago

I think the problem is that you're not destructuring

Bad:

static async getInitialProps(ctx) {}

Good:

static async getInitialProps({ ctx }) {}
andrew-oko-odion commented 5 years ago

You are right

it works well now

can we close this now