'Why do I get a UserCodeSyntaxError when I have no syntax error in my code?

I'm currently creating a Dialogflow chatbot in nodejs and upon deploying my code I get an error message. I've attempted to uncomment most things out to just be left with the base functioning code and I am still unable to get it working. I'm not exactly sure what the issue is here

'use strict';
  import {getAPIresponse} from "./api/index.js";

// const http = require('https');

// const respond = fulfillmentText => {
//   return {
//     statusCode: 200,
//     body: JSON.stringify({
//       fulfillmentText
//     }),
//     headers: {
//       "Content-Type": "application/json"
//     }
//   }
//
// };

module.exports.dining = async (event,context) => {


    const incoming= JSON.parse(event.body).queryResult;

    console.log(`INCOMING: ${incoming.parameters.hall}`);

    const {
      displayName
    } = incoming.intent;

    console.log(displayName);


    //const menu = getAPIresponse('https://esb.prod.uds.harvard.edu/api/dining/2.0/','events?locationId=36');
    //console.log(menu);
    // if(displayName === 'dining'){
    //   if(incoming.parameters.meal === 'breakfast'){
    //     //get's dining hall code to include in API request
    //     const hall = getCode(incoming.parameters.hall);
    //     //generate response from API based off of parameters passed by user
    //     const menu = getAPIresponse("https://esb.prod.uds.harvard.edu/api/dining/2.0/","events?locationId=${hall}", hall);
    //     console.log(menu);
    //   }
    //   if(incoming.parameters.meal === 'lunch'){
    //     //get's dining hall code to include in API request
    //     const hall = getCode(incoming.parameters.hall);
    //     //generate response from API based off of parameters passed by user
    //     const menu = getAPIresponse("https://esb.prod.uds.harvard.edu/api/dining/2.0","/events", hall);
    //   }
    //   if(incoming.parameters.meal === 'dinner'){
    //     //get's dining hall code to include in API request
    //     const hall = getCode(incoming.parameters.hall);
    //     //generate response from API based off of parameters passed by user
    //     const menu = getAPIresponse("https://esb.prod.uds.harvard.edu/api/dining/2.0","/events", hall);
    //   }
    // }
};

Almost everything is commented out and I still get the error message that reads

2019-07-02 16:31:33.351 (-04:00)        undefined       ERROR   Uncaught Exception  {
"errorType":"Runtime.UserCodeSyntaxError","errorMessage":"SyntaxError: Unexpected tok
en {","stack":["Runtime.UserCodeSyntaxError: SyntaxError: Unexpected token {","    at
 _loadUserApp (/var/runtime/UserFunction.js:98:13)","    at Object.module.exports.loa
d (/var/runtime/UserFunction.js:140:17)","    at Object.<anonymous> (/var/runtime/ind
ex.js:36:30)","    at Module._compile (internal/modules/cjs/loader.js:701:30)","    a
t Object.Module._extensions..js (internal/modules/cjs/loader.js:712:10)","    at Modu
le.load (internal/modules/cjs/loader.js:600:32)","    at tryModuleLoad (internal/modu
les/cjs/loader.js:539:12)","    at Function.Module._load (internal/modules/cjs/loader
.js:531:3)","    at Function.Module.runMain (internal/modules/cjs/loader.js:754:12)",
"    at startup (internal/bootstrap/node.js:283:19)"]}


Solution 1:[1]

AWS Lambda does not support the ES6 import specifier as you've written here

import {getAPIresponse} from "./api/index.js";

because the ES6 import syntax isn't yet supported by default in Node.js (note: my lambda runtime was set to Node.js 10.x).


Illustration:

I was having this issue as well when importing a library at the top of my lambda distribution's index.js file.

The stacktrace Uncaught Exception { "errorType":"Runtime.UserCodeSyntaxError", ... unexpected token import found ... blabla... } ... was thrown in my lambda function when I used the import syntax:

import awsServerlessExpress from 'aws-serverless-express';

exports.handler = (event, context) => {
  console.log('hello world!')
};

But not in this version below when I just used the standard module require syntax.

const awsServerlessExpress = require('aws-serverless-express');

exports.handler = (event, context) => {
  console.log('hello world!')
};

For me, it was the import syntax that was causing the SyntaxError exceptions, but do take note that, for you, any JavaScript syntax not supported by your current Node.js runtime will throw this exception.


A couple of solutions:

  1. Change all import statements to standard module require statements and keep using whatever default JavaScript flavour is supported by your configured Node.js runtime.

  2. Use a transpiler like Babel w/ Webpack to transpile your ES6 JavaScript before deploying to the cloud.

  3. Use the quick solution nicely described by Yitzchak below :) Just bump the NodeJS version on your Lambda Dashboard.

Solution 2:[2]

Worked for me: Updating Node.js version of lambda

I got this error because lambda was defined to execute with Node.js 12.x, when I changed it to Node.js 14.x (as on my local machine) it worked enter image description here

If it works - and you're generally using serverless package to automate deployment of your lambda - don't forget to update your serverless.yml file accordingly serverless.yml change runtime: nodejs14.x

Solution 3:[3]

In my case, I pasted code from another lambda which had node version 14. But my current lambda node version was 12. The code I pasted was using optional chaining(?.) in one line. Removed it, deployed code and it worked fine.

Solution 4:[4]

If you are using TypeScript and encounter this error make sure the target you set in tsconfig.json matches your targeted nodejs version. For a list of recommended settings visit Node Target Mapping

For example I was targeting node.js 12 and using ES2020. Changing this to ES2019 fixed my issue.

Solution 5:[5]

Sometimes in lambda, when we click on Deploy all the changes are not deployed. Refresh the page and check for syntax errors. or at least that's what was the problem in my case.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2
Solution 3 Waleed Ahmad
Solution 4
Solution 5 kumarahul