title: Firebase admin().auth().getUser(uid) internal error
body: <p><code>firebaseAdmin.auth().getUser(uid)</code> causes the following error:</p>
  
  <pre><code>Error: An internal error has occurred. Raw server response: "{}"
      at FirebaseAuthError.FirebaseError [as constructor] (/home/nowuser/src/node_modules/firebase-admin/lib/utils/error.js:39:28)
      at new FirebaseAuthError (/home/nowuser/src/node_modules/firebase-admin/lib/utils/error.js:104:23)
      at Function.FirebaseAuthError.fromServerError (/home/nowuser/src/node_modules/firebase-admin/lib/utils/error.js:128:16)
      at /home/nowuser/src/node_modules/firebase-admin/lib/auth/auth-api-request.js:364:45
      at &lt;anonymous&gt;
      at process._tickCallback (internal/process/next_tick.js:169:7)
  </code></pre>
  
  <p>This error occurs <strong>only</strong> when I deploy to production on Zeit Now; when I run my app in production mode on localhost, I do not get this error. I ensured that the app runs the same locally and on production by putting it in a Docker container.</p>
  
  <p>How can I fix this error?</p>
  
  <hr>
  
  <p>Note:</p>
  
  <p>I am aware that this question has already been posted <a href="https://stackoverflow.com/questions/40639949/firebase-admin-auth-getuseruid-error-an-internal-error-has-occurred-auth">here</a>, but the accepted answer (change the permissions of the service account) did not work for me. Also, that question does not show the full error received, so I'm not convinced it's exactly the same error. </p>
  
  <hr>
  
  <p>Update: Below is the code that pertains to this question. Basically, the server starts an express server which uses the POST authWithIdToken route to set a cookie containing the user's firebase auth idToken. It uses authenticationMiddleware to check for a cookie with idToken, and if it exists, then to decode the token and fetch the user's data. The errors occur at the getUser(uid) step. The <code>getFirebaseAdminInitConfig</code> function gets the init config, which is provided using ENV variables.</p>
  
  <pre><code># server.js - excerpt showing authentication middleware and authWithIdTokenRoute
  const server = express()
  # ...
  allowParsingPostBody(server)
  server.use(cookieParser())
  server.use('*', authenticationMiddleware)
  server.post('/authWithIdToken', authWithIdTokenRoute)
  # ...
  
  
  
  # authenticationMiddleware.js
  const { FIREBASE_ID_TOKEN_COOKIE } = require('../universal/constants')
  const firebaseAdmin = require('firebase-admin')
  const winston = require('winston')
  const getFirebaseAdminInitConfig = require('./getFirebaseAdminInitConfig')
  
  winston.info(
    'Initializing Firebase Admin with Config:',
    getFirebaseAdminInitConfig()
  )
  
  firebaseAdmin.initializeApp(getFirebaseAdminInitConfig())
  
  async function decodeToken (firebaseIdToken) {
    try {
      const decodedToken = await firebaseAdmin.auth().verifyIdToken(firebaseIdToken)
      return decodedToken
    } catch (error) {
      if (error.code !== 'auth/internal-error') throw error
      winston.warn(
        'firebase admin auth verifyIdToken auth/internal-error:',
        {
          firebaseIdToken,
          error
        }
      )
    }
  }
  
  const getFullUrl = (req) =&gt; (
    req.protocol + '://' + req.get('host') + req.originalUrl
  )
  
  const getRedirectUrl = (req) =&gt; (
    `/redirect?url=${encodeURIComponent(getFullUrl(req))}`
  )
  
  async function getUserData (uid) {
    try {
      const userData = await firebaseAdmin.auth().getUser(uid)
      return userData
    } catch (error) {
      if (error.code !== 'auth/internal-error') throw error
      winston.warn(
        'firebase admin auth getUser auth/internal-error:',
        {
          uid,
          error
        }
      )
    }
  }
  
  async function authenticationMiddleware (req, res, next) {
    const { firebaseIdToken } = req.cookies
  
    if (firebaseIdToken) {
      try {
        req.currentUserServerData = await getUserData(
          (await decodeToken(firebaseIdToken))
          .uid
        )
      } catch (error) {
        res.clearCookie(FIREBASE_ID_TOKEN_COOKIE)
  
        // if the cookie id token has expired, redirect the user to
        // /redirect?url={requestedUrl} - the client will try to set
        // a new cookie and then will redirect to requestedUrl
        if (error.code === 'auth/argument-error') {
          return res.redirect(getRedirectUrl(req))
        } else {
          winston.warn('Unexpected error occurred while processing firebase idToken:', error)
        }
      }
    }
  
    next()
  }
  
  authenticationMiddleware.authWithIdTokenRoute = async function ({body: { idToken }}, res) {
    try {
      await decodeToken(idToken)
      const expireDate = (new Date())
      expireDate.setYear((new Date()).getFullYear() + 1)
      res.cookie(FIREBASE_ID_TOKEN_COOKIE, idToken, { expires: expireDate })
      return res.send()
    } catch (error) {
      winston.warn('authWithIdTokenRoute unexpected error', {
        idToken,
        error
      })
  
      if (error.code === 'auth/argument-error') {
        return res
        .status(400)
        .send({
          error: new Error('Could not decode token')
        })
      } else {
        return res.status(500).send()
      }
    }
  }
  
  module.exports = authenticationMiddleware
  
  
  
  # getFirebaseAdminInitConfig.js
  const firebaseAdmin = require('firebase-admin')
  
  // ENV variables are set in .env file and loaded by dotenv.
  // See for more info: https://github.com/motdotla/dotenv
  const getFirebaseCredentials = () =&gt; {
    const {
      FIREBASE_TYPE: type,
      FIREBASE_PROJECT_ID: projectId,
      FIREBASE_PRIVATE_KEY_ID: privateKeyId,
      FIREBASE_PRIVATE_KEY: privateKey,
      FIREBASE_CLIENT_EMAIL: clientEmail,
      FIREBASE_CLIENT_ID: clientId,
      FIREBASE_AUTH_URI: authUri,
      FIREBASE_TOKEN_URI: tokenUri,
      FIREBASE_AUTH_PROVIDER_CERT_URL: authProviderX509CertUrl,
      FIREBASE_CLIENT_CERT_URL: clientX509CertUrl
    } = process.env
  
    return {
      type,
      projectId,
      privateKeyId,
      privateKey,
      clientEmail,
      clientId,
      authUri,
      tokenUri,
      authProviderX509CertUrl,
      clientX509CertUrl
    }
  }
  
  const getDatabaseUrl = () =&gt; {
    const { projectId } = getFirebaseCredentials()
    return `https://${projectId}.firebaseio.com`
  }
  
  module.exports = () =&gt; ({
    credential: firebaseAdmin.credential.cert(getFirebaseCredentials()),
    databaseURL: getDatabaseUrl()
  })
  </code></pre>
  
  <p>And here are the logs from my production app, deployed with Zeit Now:</p>
  
  <pre><code>08/03 08:07 AM (4m)
  REQ "GET /ka/login HTTP/2.0" 69.243.47.183 -  "" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36"
  08/03 08:07 AM (4m)
  RES "GET /ka/login HTTP/2.0" 200 3285
  08/03 08:07 AM (4m)
  REQ "GET /_next/01caf4c5-c7ab-4006-9f22-0e27366468c1/page/login HTTP/2.0" 69.243.47.183 -  "https://georgian-chant-site-dzhuccwhhp.now.sh/ka/login" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36"
  08/03 08:07 AM (4m)
  RES "GET /_next/01caf4c5-c7ab-4006-9f22-0e27366468c1/page/login HTTP/2.0" 200 37351
  08/03 08:08 AM (4m)
  REQ "GET /_next/01caf4c5-c7ab-4006-9f22-0e27366468c1/page/admin HTTP/2.0" 69.243.47.183 -  "https://georgian-chant-site-dzhuccwhhp.now.sh/ka/login" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36"
  08/03 08:08 AM (4m)
  RES "GET /_next/01caf4c5-c7ab-4006-9f22-0e27366468c1/page/admin HTTP/2.0" 200 675
  08/03 08:08 AM (4m)
  REQ "POST /authWithIdToken HTTP/2.0" 69.243.47.183 -  "https://georgian-chant-site-dzhuccwhhp.now.sh/ka/login" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36"
  08/03 08:08 AM (3m)
  debug: Successful outgoing request. Request: { port: null,
    path: '/robot/v1/metadata/x509/securetoken@system.gserviceaccount.com',
    host: 'www.googleapis.com',
    protocol: 'https:',
    auth: null,
    hostname: 'www.googleapis.com',
    hash: null,
    search: null,
    query: null,
    pathname: '/robot/v1/metadata/x509/securetoken@system.gserviceaccount.com',
    href: 'https://www.googleapis.com/robot/v1/metadata/x509/securetoken@system.gserviceaccount.com',
    method: 'GET',
    headers: { host: 'www.googleapis.com' },
    body: '' } Response:  statusCode=200, expires=Thu, 03 Aug 2017 17:45:27 GMT, date=Thu, 03 Aug 2017 10:45:53 GMT, vary=X-Origin, Origin,Accept-Encoding, content-type=application/json; charset=UTF-8, x-content-type-options=nosniff, x-frame-options=SAMEORIGIN, x-xss-protection=1; mode=block, server=GSE, cache-control=public, max-age=25174, must-revalidate, no-transform, age=4937, alt-svc=quic=":443"; ma=2592000; v="39,38,37,36,35", accept-ranges=none, connection=close, , httpVersion=1.1, url=, method=null, body={
   "{{hash retracted}}": "{{certificate retracted}}",
   "{{hash retracted}}": "{{certificate retracted}}",
   "{{hash retracted}}": "{{certificate retracted}}",
   "{{hash retracted}}": "{{certificate retracted}}""
  }
  08/03 08:08 AM (3m)
  RES "POST /authWithIdToken HTTP/2.0" 200 897
  08/03 08:08 AM (2m)
  REQ "GET /ka/admin HTTP/2.0" 69.243.47.183 -  "" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36"
  08/03 08:08 AM (2m)
  warn: firebase admin auth getUser auth/internal-error: uid={{uid retracted}}, code=auth/internal-error, message=An internal error has occurred. Raw server response: "{}"
  08/03 08:08 AM (2m)
  RES "GET /ka/admin HTTP/2.0" 302 184
  08/03 08:08 AM (2m)
  REQ "GET /ka/login HTTP/2.0" 69.243.47.183 -  "" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36"
  08/03 08:08 AM (2m)
  warn: firebase admin auth getUser auth/internal-error: uid={{uid retracted}}, code=auth/internal-error, message=An internal error has occurred. Raw server response: "{}"
  08/03 08:08 AM (2m)
  RES "GET /ka/login HTTP/2.0" 200 3285
  08/03 08:08 AM (2m)
  REQ "POST /authWithIdToken HTTP/2.0" 69.243.47.183 -  "https://georgian-chant-site-dzhuccwhhp.now.sh/ka/login" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36"
  08/03 08:08 AM (2m)
  RES "POST /authWithIdToken HTTP/2.0" 200 897
  08/03 08:08 AM (2m)
  warn: firebase admin auth getUser auth/internal-error: uid={{uid retracted}}, code=auth/internal-error, message=An internal error has occurred. Raw server response: "{}"
  08/03 08:08 AM (2m)
  REQ "POST /authWithIdToken HTTP/2.0" 69.243.47.183 -  "https://georgian-chant-site-dzhuccwhhp.now.sh/ka/login" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36"
  08/03 08:08 AM (2m)
  warn: firebase admin auth getUser auth/internal-error: uid={{uid retracted}}, code=auth/internal-error, message=An internal error has occurred. Raw server response: "{}"
  08/03 08:08 AM (2m)
  RES "POST /authWithIdToken HTTP/2.0" 200 894
  08/03 08:08 AM (2m)
  REQ "POST /authWithIdToken HTTP/2.0" 69.243.47.183 -  "https://georgian-chant-site-dzhuccwhhp.now.sh/ka/login" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36"
  08/03 08:08 AM (2m)
  RES "POST /authWithIdToken HTTP/2.0" 200 894
  08/03 08:08 AM (2m)
  warn: firebase admin auth getUser auth/internal-error: uid={{uid retracted}}, code=auth/internal-error, message=An internal error has occurred. Raw server response: "{}"
  </code></pre>
  
  <hr>
  
  <p>Update 8/15/2017: Here's the stacktrace for the error above when run with firebaseAdmin v5.2.0 (above stacktrace was for an earlier version of firebaseAdmin).</p>
  
  <pre><code>firebase admin auth getUser auth/internal-error: uid=RBwhJQy3ImStgNYvZICTT8M48Co1, code=auth/internal-error, message=An internal error has occurred. Raw server response: "{}", stacktrace=Error: An internal error has occurred. Raw server response: "{}"
      at FirebaseAuthError.FirebaseError [as constructor] (/myapp/node_modules/firebase-admin/lib/utils/error.js:39:28)
      at new FirebaseAuthError (/myapp/node_modules/firebase-admin/lib/utils/error.js:104:23)
      at Function.FirebaseAuthError.fromServerError (/myapp/node_modules/firebase-admin/lib/utils/error.js:128:16)
      at /myapp/node_modules/firebase-admin/lib/auth/auth-api-request.js:399:45
      at &lt;anonymous&gt;
      at process._tickCallback (internal/process/next_tick.js:188:7)
  </code></pre>