GithubHelp home page GithubHelp logo

netlify-lambda's Introduction

Netlify Lambda

Netlify Lambda is deprecated and we do not recommend using it anymore. Most of its functionality was moved to the Netlify CLI.

There is a detailed guide in MIGRATE.md to help you migrate away from netlify-lambda.

License

MIT

netlify-lambda's People

Contributors

8eecf0d2 avatar alexanderson1993 avatar bcomnes avatar biilmann avatar calavera avatar codepunkt avatar danez avatar dependabot[bot] avatar ehmicky avatar erezrokah avatar joe-re avatar kchung avatar kodiakhq[bot] avatar leonardodino avatar matthewalner avatar michaeldeboey avatar mikeyhogarth avatar mitchgavan avatar mottox2 avatar omonk avatar pimterry avatar renovate-bot avatar renovate[bot] avatar shmargum avatar svengau avatar swyxio avatar token-generator-app[bot] avatar verythorough avatar viniciuscamargo avatar yeojz avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

netlify-lambda's Issues

Invocations should time out in 10s

Since production functions time out in 10 seconds it would probably be a big help for local function development if netlify-lambda also timed out in 10 seconds by default. That would prevent surprises for any folks who may have missed that section of the functions/Lambda documentation.

Logging

First of this is awesome. Only one thing that seems to have me stumped is logging. I have a number of console.log statements in my functions, however when they are executed in production in the functions console in the netlify dashboard I only see something like this

7:42:55 AM: locations invoked
7:51:43 AM: locations invoked

I have also tried a number of other loggers https://github.com/winstonjs/winston & https://github.com/pinojs/pino but with no luck.

Is there some sort of environment variable I need to set or some other trick to get logging working in production?

Thanks in advance.

Running `serve` overwrites original lambda

When running netlify-lambda serve functions/, the command keeps compiling the functions infinitely, bloating and overwriting the original files with every compilation.

I ran the command in the code-examples repo, notice the filesize growing bigger and bigger.

$ ./node_modules/.bin/netlify-lambda serve functions/
Starting server
Lambda server is listening on 9000
Hash: da984e20aebc1ac3f751
Version: webpack 3.11.0
Time: 431ms
    Asset     Size  Chunks             Chunk Names
random.js  2.98 kB       0  [emitted]  random
   [0] ./functions/random.js 424 bytes {0} [built]
Hash: 7369ba5e43bd2af7c5a1
Version: webpack 3.11.0
Time: 23ms
    Asset     Size  Chunks             Chunk Names
random.js  5.74 kB       0  [emitted]  random
   [0] ./functions/random.js 3.18 kB {0} [built]
Hash: f6e8fafb802d3919efd1
Version: webpack 3.11.0
Time: 16ms
    Asset     Size  Chunks             Chunk Names
random.js  8.68 kB       0  [emitted]  random
   [0] ./functions/random.js 6.12 kB {0} [built]
Hash: 77035ca7b401471403d9
Version: webpack 3.11.0
Time: 21ms
    Asset     Size  Chunks             Chunk Names
random.js  11.8 kB       0  [emitted]  random
   [0] ./functions/random.js 9.23 kB {0} [built]
Hash: b5edcfb7c37f7dd11bb8
Version: webpack 3.11.0
Time: 22ms
    Asset     Size  Chunks             Chunk Names
random.js  15.1 kB       0  [emitted]  random
   [0] ./functions/random.js 12.5 kB {0} [built]
Hash: 1ed77f22dbd1c977cbb5
Version: webpack 3.11.0
Time: 24ms
    Asset     Size  Chunks             Chunk Names
random.js  18.6 kB       0  [emitted]  random
   [0] ./functions/random.js 16 kB {0} [built]
Hash: c997d31cc2030de2d4a6
Version: webpack 3.11.0
Time: 20ms
    Asset     Size  Chunks             Chunk Names
random.js  22.2 kB       0  [emitted]  random
   [0] ./functions/random.js 19.6 kB {0} [built]

...

The original function files are also modified, see running git status right after serve:

$ git status
On branch master
Your branch is up-to-date with 'origin/master'.
Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

	modified:   functions/random.js

random.js is overwritten with compiled code. This is with the package [email protected].

Discussion - PayloadTooLargeError: request entity too large

Got this error when testing my function locally by sending a ~160kb POST request. This error doesn't happen when deployed on Netlify functions though.

This is due to express server with it's default limit and could be altered via middlewares. Could we allow express middlewares from netlify-lambda users via netlify-lambda-serve.js or similar mechanism for flexibilities?

Cannot find module 'fs.realpath' react-scripts build

I tried out your create react app inspired repo for the lambda functions and everything runs and builds fine locally, but when I try to run a deploy on netlify I get the errors below. I modified from yarn to npm run as you'll see below but got the same error for both. I also tried with the defautl node version which was 8 something but currently have it set to 9.4.0 and same errors on both.

10:23:11 AM: [4/4] Building fresh packages...
10:23:11 AM: Done in 22.33s.
10:23:11 AM: NPM modules installed using Yarn
10:23:12 AM: Installing missing commands
10:23:12 AM: Executing user command: npm run build && npm run build:lambda
10:23:12 AM: > [email protected] build /opt/build/repo
10:23:12 AM: > react-scripts build
10:23:14 AM: module.js:557
10:23:14 AM:     throw err;
10:23:14 AM:     ^
10:23:14 AM: Error: Cannot find module 'fs.realpath'
10:23:14 AM:     at Function.Module._resolveFilename (module.js:555:15)
10:23:14 AM:     at Function.Module._load (module.js:482:25)
10:23:14 AM:     at Module.require (module.js:604:17)
10:23:14 AM:     at require (internal/module.js:11:18)
10:23:14 AM:     at Object.<anonymous> (/opt/build/repo/node_modules/glob/glob.js:44:10)
10:23:14 AM:     at Module._compile (module.js:660:30)
10:23:14 AM:     at Object.Module._extensions..js (module.js:671:10)
10:23:14 AM:     at Module.load (module.js:573:32)
10:23:14 AM:     at tryModuleLoad (module.js:513:12)
10:23:14 AM:     at Function.Module._load (module.js:505:3)
10:23:14 AM:     at Module.require (module.js:604:17)
10:23:14 AM:     at require (internal/module.js:11:18)
10:23:14 AM:     at Object.<anonymous> (/opt/build/repo/node_modules/rimraf/rimraf.js:7:12)
10:23:14 AM:     at Module._compile (module.js:660:30)
10:23:14 AM:     at Object.Module._extensions..js (module.js:671:10)
10:23:14 AM:     at Module.load (module.js:573:32)
10:23:14 AM: npm ERR! code ELIFECYCLE
10:23:14 AM: npm ERR! errno 1
10:23:14 AM: npm ERR! [email protected] build: `react-scripts build`
10:23:14 AM: npm ERR! Exit status 1
10:23:14 AM: npm ERR!
10:23:14 AM: npm ERR! Failed at the [email protected] build script.
10:23:14 AM: npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
10:23:14 AM: npm ERR! A complete log of this run can be found in:
10:23:14 AM: npm ERR!     /opt/buildhome/.npm/_logs/2018-02-08T15_23_14_046Z-debug.log
10:23:14 AM: Caching artifacts
10:23:14 AM: Cached NPM modules
10:23:14 AM: Saved Yarn cache
10:23:14 AM: Build complete: exit code: 1
10:23:14 AM: Error running command: Build script returned non-zero exit code: 1
10:23:14 AM: Failing build: Failed to build site
10:23:15 AM: failed during stage 'building site': Build script returned non-zero exit code: 1
10:23:15 AM: Finished processing build request in 39.965670133s```

Third party libraries not working in function

I'm trying to use node-fetch in my function but keep getting the Cannot find module 'node-fetch' error. This error only happens on a deployed function but works locally.

func.js

const fetch = require('node-fetch');

exports.handler = async (event, context) => {
	const result = await fetch('www.google.com', {
		method: 'GET',
	}).catch((err) => {
		// boo hoo
	});

	return {
		statusCode: 200,
		body: 'Badabing badaboom.'
	};
};

My folder structure is

netlify-functions/
    func.js
package.json

any ideas?

Webpack errors on serve and build.

I'm seeing some errors that appear to be related to webpack when I run serve and build. Here's a sample repository (this link is to a tag I created, in case I make any changes between now and when somebody gets a chance to take a look): https://github.com/brianmcallister/functions-test/releases/tag/test-build

Here's what I'm seeing:

When I run npx netlify-lambda serve ., I see the following message:

netlify-lambda: Starting server
Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema.
 - configuration.entry should be one of these:
   function | object { <key>: non-empty string | [non-empty string] } | non-empty string | [non-empty string]
   -> The entry point(s) of the compilation.
   Details:
    * configuration.entry should be an instance of function
      -> A Function returning an entry object, an entry string, an entry array or a promise to these things.
    * configuration.entry should not be empty.
      -> Multiple entry bundles are created. The key is the chunk name. The value can be a string or an array.
    * configuration.entry should be a string.
      -> An entry point without name. The string is resolved to a module which is loaded upon startup.
    * configuration.entry should be an array:
      [non-empty string]
Lambda server is listening on 9000

...and when I GET localhost:9000/test, the server is responding correctly.

However, when I run npx netlify-lambda build ., I see the following:

netlify-lambda: Building functions
WebpackOptionsValidationError: Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema.
 - configuration.entry should be one of these:
   function | object { <key>: non-empty string | [non-empty string] } | non-empty string | [non-empty string]
   -> The entry point(s) of the compilation.
   Details:
    * configuration.entry should be an instance of function
      -> A Function returning an entry object, an entry string, an entry array or a promise to these things.
    * configuration.entry should not be empty.
      -> Multiple entry bundles are created. The key is the chunk name. The value can be a string or an array.
    * configuration.entry should be a string.
      -> An entry point without name. The string is resolved to a module which is loaded upon startup.
    * configuration.entry should be an array:
      [non-empty string]
    at webpack (/Users/brianmcallister/projects/functions-test/node_modules/webpack/lib/webpack.js:31:9)
    at /Users/brianmcallister/projects/functions-test/node_modules/netlify-lambda/lib/build.js:93:5
    at new Promise (<anonymous>)
    at Object.exports.run (/Users/brianmcallister/projects/functions-test/node_modules/netlify-lambda/lib/build.js:92:10)
    at Command.<anonymous> (/Users/brianmcallister/projects/functions-test/node_modules/netlify-lambda/bin/cmd.js:51:8)
    at Command.listener (/Users/brianmcallister/projects/functions-test/node_modules/commander/index.js:315:8)
    at Command.emit (events.js:180:13)
    at Command.parseArgs (/Users/brianmcallister/projects/functions-test/node_modules/commander/index.js:654:12)
    at Command.parse (/Users/brianmcallister/projects/functions-test/node_modules/commander/index.js:474:21)
    at Object.<anonymous> (/Users/brianmcallister/projects/functions-test/node_modules/netlify-lambda/bin/cmd.js:61:9)

According to the documentation, it doesn't appear as though I need to provide any custom webpack config at all, but let me know if I'm misunderstanding something.

Async handlers produce unhandled promise rejection warnings

Test Repo

I'm getting warnings about unhandled promise rejection when using async handler functions like below.

exports.handler = async (event, context, callback) => {
  callback(null, {
    statusCode: 200,
    body: JSON.stringify({ success: true }),
  });
}

I've also tried using Promise.Resolve() with the response object.

exports.handler = async (event, context, callback) => {
  Promise.resolve({
    statusCode: 200,
    body: JSON.stringify({ success: true }),
  });
}

My understanding is that either should work with node 8.10.x lambda instances but the netlify-lambda serve console produces the following warning:

UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'statusCode' of undefined
    at callback (/Users/lloyd/dev/netlify-lambda-async-test/node_modules/netlify-lambda/lib/serve.js:22:42)
    at /Users/lloyd/dev/netlify-lambda-async-test/node_modules/netlify-lambda/lib/serve.js:41:21
    at <anonymous>
    at process._tickCallback (internal/process/next_tick.js:182:7)
(node:56861) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)

Check for source vs publish path to not be same location

Before I start, promise not to laugh (too hard).

Issue

  1. Copied the example hello.js into the functions folder
  2. Made a scripts command in package.json called start : "start": "netlify-lambda serve functions"
  3. netlify.toml has functions = "functions" under the build

When running the yarn start command, the build picks up the source and start overwriting with the bundle. It watches and builds again, causing an infinite loop.

Expected behavior

Would be great to get a message "source and publish folder should be in different locations"

compiled functions not showing on the netlify>>functions dashboard

I am working on a gatsby site, deployed via github on Netlify.

i've added 2 lambda functions in src/functions

they get built and compiled to /lambda
I can see both of them there, duly compiled.

however when i push to github and it gets deployed I can only see one of the two lambda function files. No matter how I change the names this remains the case. for now the content of each of the files is identical, but just wanted to test two endpoints : getusers.js and sandbox.js

Both works when i locally serve the functions. but once pushed only sandbox shows up on the Netlify dashboard (and works when i hit the /.netlify/functions/sandbox endpoint).

Thanks for your help!

Use .babelrc in function folder first

Would be nice if .babelrc is first looked (or only looked?) into the folder of the functions.
Root folder may contains .babelrc used by other part of the project.

Add `shebang-loader` by default?

There are some node modules that begin with a shebang and current setup fails to consume those properly failing with:

[functions] Error during invocation:  Error: Module parse failed: Unexpected character '#' (1:0)
[functions] You may need an appropriate loader to handle this file type.
[functions] | #!/usr/bin/bin/env node

The shebang-loader loader fixes the issue.

I fixed it by adding a custom config override, but it'd be probably beneficial for others too.

If you want me to submit a PR, let me know I can do that.

Cannot find @babel/core

I’ve been using netlify-lambda and it throws an error whenever I use β€œserve”.

Nicholas@Patriot MINGW64 ~
$ node -v
v8.10.0

Nicholas@Patriot MINGW64 ~
$ npm -v
5.6.0

The full error is:

ERROR in ./subscribe.js
Module build failed: Error: Cannot find module '@babel/core'
    at Function.Module._resolveFilename (module.js:547:15)
    at Function.Module._load (module.js:474:25)
    at Module.require (module.js:596:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (C:\Users\Nicholas\projects\personal\emails.humanwhocodes.com\node_modules\babel-loader\lib\transform.js:1:75)
    at Module._compile (module.js:652:30)
    at Object.Module._extensions..js (module.js:663:10)
    at Module.load (module.js:565:32)
    at tryModuleLoad (module.js:505:12)
    at Function.Module._load (module.js:497:3)
    at Module.require (module.js:596:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (C:\Users\Nicholas\projects\personal\emails.humanwhocodes.com\node_modules\babel-loader\lib\cache.js:24:17)
    at Module._compile (module.js:652:30)
    at Object.Module._extensions..js (module.js:663:10)
    at Module.load (module.js:565:32)

This happens right at startup when testing locally and no functions will work. The function in this example simply prints out β€œOK”.

Is there something missing in the package for netlify-lambda?

Invalid webpack config

The documentation doesn't say anything about a required webpack config, either the config in build.js is wrong, or there has to be a webpack config:

> # netlify-lambda build functions                                                                                                                                                                               
Building functions
WebpackOptionsValidationError: Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema.
 - configuration.entry should be one of these:
   object { <key>: non-empty string | [non-empty string] } | non-empty string | [non-empty string] | function
   -> The entry point(s) of the compilation.
   Details:
    * configuration.entry should not be empty.
      -> Multiple entry bundles are created. The key is the chunk name. The value can be a string or an array.
    * configuration.entry should be a string.
      -> An entry point without name. The string is resolved to a module which is loaded upon startup.
    * configuration.entry should be an array:
      [non-empty string]
    * configuration.entry should be an instance of function
      -> A Function returning an entry object, an entry string, an entry array or a promise to these things.
    at webpack (/usr/lib/node_modules/netlify-lambda/node_modules/webpack/lib/webpack.js:19:9)
    at /usr/lib/node_modules/netlify-lambda/lib/build.js:93:5
    at new Promise (<anonymous>)
    at Object.exports.run (/usr/lib/node_modules/netlify-lambda/lib/build.js:92:10)
    at Command.<anonymous> (/usr/lib/node_modules/netlify-lambda/bin/cmd.js:48:8)
    at Command.listener (/usr/lib/node_modules/netlify-lambda/node_modules/commander/index.js:315:8)
    at emitTwo (events.js:126:13)
    at Command.emit (events.js:214:7)
    at Command.parseArgs (/usr/lib/node_modules/netlify-lambda/node_modules/commander/index.js:651:12)
    at Command.parse (/usr/lib/node_modules/netlify-lambda/node_modules/commander/index.js:474:21)

Running `serve` command wipes out function code

Hopefully I'm not missing a configuration option or something...

When I run the serve command, the code in my /functions/whatever.js appears to be processed by Webpack, wiping out the precompiled code I had written. As a makeshift solution, I've wrapped been first copying the precompiled file to a different directory to preserve it, but would not like to keep that up long term.

Time out issue

I don't run into any issues with my built function locally. It runs immediately.

But when deployed on Netlify, I'm getting a time out error:

{"errorMessage":"2018-12-17T02:49:11.602Z 4f290cff-01a6-11e9-934d-9f4eca498414 Task timed out after 10.01 seconds"}

Any clues what could be wrong? Or else - how do I debug this?

Information:

  1. Nothing in the deployment logs indicates that something's wrong in the build.
  2. Here is my netlify.toml:
[build]
  command = "yarn lambda:build"
  functions = "functions"
  1. Here is my package.json:

{
  "name": "netlify-backend-starter-kit",
  "version": "1.0.0",
  "description": "",
  "main": "src/index.js",
  "license": "UNLICENSED",
  "scripts": {
    "lambda:build": "netlify-lambda build src/lambda",
    "lambda:serve": "netlify-lambda serve src/lambda"
  },
  "dependencies": {
    "graphql-shield": "^4.1.2",
    "graphql-yoga": "^1.16.7"
  },
  "devDependencies": {
    "@babel/cli": "^7.2.0",
    "@babel/core": "^7.2.0",
    "@babel/node": "^7.2.0",
    "@babel/plugin-transform-runtime": "^7.2.0",
    "@babel/preset-env": "^7.2.0",
    "netlify-lambda": "^1.1.1",
  }
}

Custom webpack config

Thanks for adding support for this in Version 0.2.0.

I believe this was only added for the build, not serve command. If you look at line 63 of build.js you see that additionalConfig is passed to webpackConfig, however in lines 73 and 74 additionalConfig is not passed. The result is that custom webpack configs are incorporated when running build -c, but not when running serve -c.

Cannot find module

I followed the tutorial exactly:

  1. yarn add netlify-lambda in a new directory
  2. create a file called 'netlify.toml' with the contents
[build]
  functions = "functions"
  1. created the file src/hello.js with the contents:
exports.handler = function(event, context, callback) {
    callback(null, {
    statusCode: 200,
    body: "Hello, World"
    });
}
  1. Ran netlify-lambda serve src and got:
Unhandled rejection Error: Cannot find module '<redacted>/functions/hello'

Am I missing something here?

Serve the full website

I think it would be better to:

  • server the full website (easier to test lambda functions in context)
  • server the function with the /.netlify/functions/ path)
  • parse .env to set environment variables

I did it here for personal use, I can PR it if it make sense for others.

Uploading files with multipart/form-data fails

When sending a POST request with Postman using multipart/form-data and attaching a file to the request it results in InvalidCharacterError originating from base-64 which is a dependency of netlify-lambda used to decode event.body when creating handler.

Works in prod environment.

Adding additional webpack loaders

Hi there

I'm trying to compile a function, that uses a soap module, with netlify-lambda without success, giving me the following warning:

WARNING in ./lambda-test/node_modules/ejs/lib/ejs.js
require.extensions is not supported by webpack. Use a loader instead.

I know that it's possible to add additional webpack loaders, that is what I tried to do using https://github.com/bazilio91/ejs-compiled-loader but I cannot sort it out.

Any hints from your side?
Many thanks

Usage in monorepo

I have a lerna monorepo.

My functions package is in packages/functions. My functions source is in packages/functions/src. I build the functions with netlify-lambda via a script in the file packages/functions/package.json. I want the functions to be build to packages/functions/build so I add a netlify.toml with this content:

[build]
  functions = "build"

When I run netlify-lambda serve ./src from packages/functions all is fine. I also add a postinstall script to run netlify-lambda build ./src which creates the correct files in packages/functions/build when yarn is run.

But when I try to deploy to netlify, netlify takes the netlify.toml from the folder packages/functions and tries to find the functions in build (at the project root) and finds no functions.

If I do not commit the netlify.toml (to just use it locally), the postinstall script does not work any more, because it requires a netlify.toml (in package/functions).

So baseline is: One cannot use this tool with a monorepo.

I suggest to stop (ab)using the netlify.toml for a build configuration and make the cli tool take two parameters:

netlify-lambda build src target

Lambda built code unstable with some packages

EDIT: The problem is that the lambda repeatedly throws different errors indicating that the built code is highly unstable.

Originally it seemed like process.cwd() was returning C:/.

It appeared that the issue began after I installed Python 2.7, set the PYTHON environment var, then ran 'npm install --global --production windows-build-tools' to get node-gyp working properly.

But I was mistaken:
Not sure if it's because of one of Google Cloud Datastore's dependencies, but the lambdas actually seem to perform just fine if I don't require that particular package.

But if I do require it, it seems like the resultant build is missing modules, as the built code looks like this (which, as you know, will always fail to execute)
image

Dev environment differs from production

Hello - I've noticed two issues where this dev environment package differs from the Netlify production environment in how the body of a POST call is treated.

Base64
In the production environment, event.body is a JSON string. In the dev environment, event.body is in Base64 and needs to be decoded into a JSON string. It would be helpful if the event.body was either Base64 or JSON string in both so functions work the same in both environments.

Body Types
The production environment accepts all types of body types (application/json, application/text, etc).
In the dev environment, only application/octet-stream is accepted. If a user POSTS data of say application/json, then that data is disregarded and event.body is an empty object (in Base64). This is due to line 68 of serve.js - app.use(bodyParser.raw()). When no type is specified for raw, the default is type: 'octet-stream'. Recommend a broader set of accepted types or even something like app.use(bodyParser.raw({type: () => true})) to accept all POST types.

Running tests/CI suite

I may be missing an obvious configuration option.

For running this server for testing, how would one ensure that the webpack watch stops executing so everything can exit correctly?

I can add a pull request that adds another cli command, something like start:ci or something like that.

[Good first issue] better error message when body is undefined

splitting out @waynehoover's issue from here: #43 (comment)

when you do this:

exports.handler = async function(event, context) {
    let body = parse(event.body)
    await doSomeAsyncWorkHere();
    return {
      statusCode: 301,
		// oops no body
    }
}

you get this:

(node:26997) UnhandledPromiseRejectionWarning: TypeError [ERR_INVALID_ARG_TYPE]: The first argument must be one of type string or Buffer. Received type undefined
    at write_ (_http_outgoing.js:607:11)
    at ServerResponse.write (_http_outgoing.js:579:10)
    at callback (/Users/.../node_modules/netlify-lambda/lib/serve.js:26:14)
    at /Users/.../node_modules/netlify-lambda/lib/serve.js:41:21
    at process.internalTickCallback (internal/process/next_tick.js:77:7)
(node:26997) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:26997) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
Hash: ec967454cf2cf833f214

we should basically insert an undefined check here: https://github.com/netlify/netlify-lambda/blob/master/lib/serve.js#L29 and serve a friendly warning

should also thinking about other forms of validation

environment context variables do not override build variables

If you define environment variables in the netlify.toml only the build.environment variables are being used.

Eg:

[build.environment]
  GREETING="Hello World! I am a variable set in a .env file"

# When building on the production environment this variable will NOT be used.
[context.production.environment]
  GREETING="production greeting"

npm start:lambda doesn't work -> answer: use npm run start:lambda

I was following the instructions here: https://www.netlify.com/docs/functions/#configuring-the-functions-folder

and installed netlify-lambda with:
npm install netlify-lambda

Then I created the appropriate netlify.toml file, but when I go to run with netlify-lambda serve I get the follow error:

Patrick$ netlify-lambda serve src/lambda
-bash: netlify-lambda: command not found

I checked and netlify-lambda is present the node_modules folder, so I'm not sure what I did wrong.

Thanks for the help.

NPM version: 5.6.0
node version: v8.11.4

Udpate: I also tried cloning the https://github.com/netlify/create-react-app-lambda repo, and then installed the dependencies with npm, and then tried to netlify-lambda serve, and I got the same error.

Request to allow return of an object or string instead of response, assuming 200

With Node 8.10 and #24 merged in to 0.4.0, we can now return promises πŸ‘Œ (thanks @leonardodino)

However, it doesn’t behave the same way Lambda does.

Using 8.10, you can return a promise to Lambda. It reads the resolve as being a 200 (with the body), and a reject as a 500 (with the error).

However Netlify Lambda this doesn’t work yet:

Response with status NaN in 0 ms.
(node:6095) UnhandledPromiseRejectionWarning: RangeError [ERR_HTTP_INVALID_STATUS_CODE]: Invalid status code: undefined
    at ServerResponse.writeHead (_http_server.js:201:11)
    at ServerResponse.writeHead (/Users/thomas/Sites/netlify-lambda-promise-test/node_modules/on-headers/index.js:55:19)
    at ServerResponse._implicitHeader (_http_server.js:192:8)
    at write_ (_http_outgoing.js:637:9)
    at ServerResponse.write (_http_outgoing.js:622:10)
    at callback (/Users/thomas/Sites/netlify-lambda-promise-test/node_modules/netlify-lambda/lib/serve.js:26:14)
    at /Users/thomas/Sites/netlify-lambda-promise-test/node_modules/netlify-lambda/lib/serve.js:43:7
    at <anonymous>
    at process._tickCallback (internal/process/next_tick.js:160:7)
(node:6095) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)

This is using the test project I created to test with.

This should work, but just times out with the above error:

exports.handler = async event => {
    return new Promise((resolve, reject) => {
        resolve("yay!");
    });
};

This does work:

exports.handler = async event => {
    return new Promise((resolve, reject) => {
        resolve({ statusCode: 200, body: "yay!" });
    });
};

So promises are being resolved, but it's not allowing it to return a promise. Now I’m new to promises, so this suggestion might be wrong or there might be a better way, but if we change this:

promise.then(
  function(data) {
    callback(null, data);
  },
  function(err) {
    callback(err, null);
  }
);

to this:

promise.then(
  function(data) {
    callback(null, { statusCode: 200, body: data });
  },
  function(err) {
    callback(err, null);
  }
);

Then it will work – but I’m not sure how safe this is or if it’s a good idea or not.

Getting netlify-lambda working with React-Router

I'm getting difficulties while configuring a proxy working with React-Router to use a proxy cohabiting with my existing routes.

Is it possible to set up an equivalent to a Route with a path like /.netlify/functions/${lambda-func} to handle lambda calls, via the proxy (to http://localhost:9000 for instance) inside a React application with React-Router?

Thanks in advance.

Handlers that serve images results in 500

A 500 results when creating a handler that writes an image buffer to the output:

exports.handler = function (event, context, callback) {

var outputBuffer = // ... image buffer stuff

var response = {
    statusCode: 200,
    headers: {'Content-Type' : 'image/png'},
    body: outputBuffer.toString('base64'),
    isBase64Encoded: true
}

callback(null, response)

}

[BUG] Babel-loader - hidden dependency

after running command ./node_modules/.bin/netlify-lambda build functions-source/
I god

netlify-lambda: Building functions
Hash: 2f36233598c9262552e4
Version: webpack 4.20.2
Time: 1142ms
Built at: 2018-10-16 12:47:52
    Asset      Size  Chunks  Chunk Names
rating.js  1.21 KiB       0  rating
Entrypoint rating = rating.js
[0] ./rating.js 254 bytes {0} [built] [failed] [1 error]

ERROR in ./rating.js
Module build failed (from ../node_modules/babel-loader/lib/index.js):
TypeError: Cannot read property 'babel' of undefined
    at Object.module.exports (/Users/nikolay/Projects/autokwix/node_modules/babel-loader/lib/index.js:103:36)

after installing babel-loader - it started to work

how on earth?

Debug lambda functions locally

Hi,

is there a way to debug lambda functions locally? I already looked in the docs, but did't find anything which points in that direction.

I'm missing the ability to set an --inspect flag (which is common when debugging node applications) or something similar to start a debug mode, when serving my lamdba functions with netlify-lambda serve.

I know that I can log everything with console.log(), but this can be a bit tedious.

Am I missing something here?
Any help would be greatly appreciated!

command line error message is confusing when toml file is missing publish property

using version 0.4.0 via npm, neither serve or build commands recognize the given argument:

> netlify-lambda serve x
Starting server
path.js:28
    throw new TypeError('Path must be a string. Received ' + inspect(path));
    ^

TypeError: Path must be a string. Received undefined
    at assertPath (path.js:28:11)
    at Object.join (path.js:1246:7)
    at webpackConfig (/Users/rabbah/.node/lib/node_modules/netlify-lambda/lib/build.js:36:28)
    at Object.exports.watch (/Users/rabbah/.node/lib/node_modules/netlify-lambda/lib/build.js:103:26)
    at Command.<anonymous> (/Users/rabbah/.node/lib/node_modules/netlify-lambda/bin/cmd.js:28:11)
    at Command.listener (/Users/rabbah/.node/lib/node_modules/netlify-lambda/node_modules/commander/index.js:315:8)
    at emitTwo (events.js:126:13)
    at Command.emit (events.js:214:7)
    at Command.parseArgs (/Users/rabbah/.node/lib/node_modules/netlify-lambda/node_modules/commander/index.js:651:12)
    at Command.parse (/Users/rabbah/.node/lib/node_modules/netlify-lambda/node_modules/commander/index.js:474:21)
> netlify-lambda build x
Building functions
TypeError: Path must be a string. Received undefined
    at assertPath (path.js:28:11)
    at Object.join (path.js:1246:7)
    at webpackConfig (/Users/rabbah/.node/lib/node_modules/netlify-lambda/lib/build.js:36:28)
    at /Users/rabbah/.node/lib/node_modules/netlify-lambda/lib/build.js:93:13
    at new Promise (<anonymous>)
    at Object.exports.run (/Users/rabbah/.node/lib/node_modules/netlify-lambda/lib/build.js:92:10)
    at Command.<anonymous> (/Users/rabbah/.node/lib/node_modules/netlify-lambda/bin/cmd.js:48:8)
    at Command.listener (/Users/rabbah/.node/lib/node_modules/netlify-lambda/node_modules/commander/index.js:315:8)
    at emitTwo (events.js:126:13)
    at Command.emit (events.js:214:7)

queryStringParameters object structure differs from deployment environment

We have a request that looks something like this:

?filter[0][field]=title&filter[0][value]=TestElement&filter[1][field]=category&filter[1][value]=CategoryName

And in the development environment's lambda function the event.queryStringParameters, will be a nested object/array construct like this:

{
    "filter": [
        {
            "field": "title",
            "value": "TestElement"
        },
        {
            "field": "category",
            "value": "CategoryName"
        }
    ]
}

But in our deployment environment it will be a flat object like this:

{
    "filter[0][field]" : "title",
    "filter[0][value]" : "TestElement",
    "filter[1][field]" : "category",
    "filter[1][value]" : "CategoryName"
}

It should be the same in both environments.

Function invocation failed: TypeError: n is not a function

Hi there,
I'm attempting to use a lambda function to use the node wpapi library
https://github.com/WP-API/node-wpapi

For some reason when I try to instantiate a new instance of their WPAPI class I get the error Function invocation failed: TypeError: n is not a function

I don't believe this is a problem with netlify-lambda but I'm wondering if someone could give me some guidance on debugging this. Is there something I need to add to my config to make it run? Or is there some way for me to figure out why n is not a function? The error comes from the minified code so it's hard to understand what's happening

Document setup

Hi there!

It is really troublesome to get started with this CLI.
First I run the CLI - netlify-lambda serve functions
And get the error - babel-loader is missing.
As I install more and more missing dependencies (there is not a single note of required packages in order to run this... Netlify also just documents that files are named after functions.
E.g. functions/test.js will be served as domain.netlify.com/.netlify/functions/test
No webpack setup required at all.

So please document the proper setup required in order to run this CLI. Thanks

Features from netlify-local

As per email discussions...

I'm the maintainer of 8eecf0d2/netlify-local and would like to discuss some ideas for merging features from there and into here.

The goal of netlify-local is to emulate all appropriate Netlify features for the purpose of local development (some features such as Identity might not make sense to emulate locally), whereas netlify-lambda appears to focus on the Netlify Functions feature specifically.

From what I can tell, there are no major differences between netlify-lambda and netlify-local in terms of emulating Netlify Functions and the implementations are functionally the same.

Because of this there aren't many meaningful features within the scope of netlify-lambda that could be brought over from netlify-local, so for any features to be merged I'd suggest that netlify-lambda's scope should be increased (so that features can be merged) or potentially netlify-local could be transferred across to Netlify in it's entirety.

If a scope increase or ownership transfer sounds reasonable, I think the following issues should be figured out before hand.

  • Explore the idea proposed in 8eecf0d2/netlify-local#12 where the configuration options can be defined within netlify.toml under a plugins property (storing configuration options in command line arguments is a pain imo).
  • Finish (correctly) implementing the Redirect / Static Server features from 8eecf0d2/netlify-local#8.
  • Better document the supported features of the package (Static Server, Redirect, Headers, Lambdas) and how to use them.
  • Expose an API for running the package programatically (mostly implemented in netlify-local).
  • Improve the built-in bundling features to:
    • Only do the bare minimum required for bundling.
    • Support custom Webpack configurations (without merging).
    • Allow more declarative configuration for bundling (eg, plugin.local.functions).
    • Expose an API to the same effect of 8eecf0d2/webpack-netlify-lambda-plugin.

Thanks for reading, look forward to your thoughts 😊

process.env not completely passed to DefinePlugin

During the build process the system reads the envrionment variables from the toml config, but will not include environment variables defined inside of the Environment panel in netlify or any environment variables defined within the build process. I added a additionalConfig webpack and define a new DefinePlugin.

bash: netlify-lambda: command not found

Installed netlify-lambda into project directory using npm
npm install netlify-lambda

But when I try to use it:
netlify-lambda serve <folder>

I see
bash: netlify-lambda: command not found

I've also tried in a windows command prompt

Windows 10
Node: v8.9.1
NPM: v5.4.2

Typescript local import

I made a quick test project to try out the new Typescript support structure looks like this.

.
β”œβ”€β”€ functions
β”‚Β Β  β”œβ”€β”€ jokeTypescript.js
β”‚Β Β  └── jokeVanilla.js
β”œβ”€β”€ netlify.toml
β”œβ”€β”€ package.json
β”œβ”€β”€ src_functions
β”‚Β Β  β”œβ”€β”€ jokeTypescript.ts
β”‚Β Β  β”œβ”€β”€ jokeVanilla.js
β”‚Β Β  └── utils
β”‚Β Β      └── direction.ts
└── yarn.lock

when I try to import something local like this

import { Direction } from './utils/direction';

in jokeTypescript.ts, I get an error in the build like this

ERROR in ./jokeTypescript.ts
Module not found: Error: Can't resolve './utils/direction' in '/Users/matt/sandbox/nl-test/src_functions'
 @ ./jokeTypescript.ts 6:0-46 19:21-30

external imports like import * as request from 'request-promise-native'; seem to work though

any thoughts?

Does Netlify Lambda support sub-directory ?

Hi,

I tried to use a sub-directory, such as ./netlify/functions/hello/world.js, and I expect the url would be localhost:9000/hello/world.

But I failed and I found nothing in the docs related to this issue.

So, I'd like to confirm that whether or not the Netlify lambda function supports such feature ? Thanks.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.