Search code examples
javascriptnode.jsexpressauth0

Errors running sample code - Class within an exported class - Auth0 with React Node.js


I am trying to run tutorial code for creating an authentication serve into my React project.

Here is the code sample that they want me to run:

// src/Auth/Auth.js

import auth0 from 'auth0-js';

export default class Auth {
  auth0 = new auth0.WebAuth({
    domain:'domain.auth0.com',
    clientID: 'clientId',
    redirectUri: 'http://localhost:3000/callback',
    audience: 'https://myproject.auth0.com/userinfo',
    responseType: 'token id_token',
    scope: 'openid'
  });

  login() {
    this.auth0.authorize();
  }
}

When I ran it, it throws errors about the 'import' and export' keywords. So I changed it to this:

const auth0 = require("auth0-js");

class Auth {
    auth = new auth0.WebAuth({
        domain: 'mydomain.auth0.com',
        clientID: 'clientID',
        redirectUri: 'http://localhost:3000/callback',
        audience: 'https://myproject.auth0.com/userinfo',
        responseType: 'token id_token',
        scope: 'openid'
  });

  login() {
    this.auth.authorize();
  }
}

module.exports = Auth;

But that gives me this error:

/Users/myname/my project/app/services/auth.js:4
    auth = new auth0.WebAuth({
         ^


SyntaxError: Unexpected token =
    at createScript (vm.js:80:10)
    at Object.runInThisContext (vm.js:139:10)
    at Module._compile (module.js:616:28)

What is the correct syntax?


Solution

  • instance class fields are only supported in node >= 10 using --harmony flag.

    You can use a getter instead, that it is supported without any flag.

    class Auth {
    
        get auth() {
            if(!this._auth) {
                this._auth = new auth0.WebAuth({ /* ... */ });
            }
    
            return this._auth;
        }
    
        login() {
            this.auth.authorize();
        }
    }
    

    Or just set it inside the constructor

    class Auth {
    
        constructor() {
    
            this.auth = new Auth0.WebAuth({ /* ... */ });
        }
    }
    

    Or you can use babel to transpile your code.