UNPKG

25.1 kBMarkdownView Raw
1## Netlify Lambda
2
3This is an optional tool that helps with building or locally developing [Netlify Functions](https://www.netlify.com/docs/functions/) with a simple webpack/babel build step.
4
5The goal is to make it easy to write Lambda's with transpiled JS/TypeScript features and imported modules.
6
7<details>
8 <summary><b>Multiple ways to deploy functions on Netlify</b></summary>
9
10There are 3 ways to deploy functions to Netlify:
11
121. each function as a single JS or Go file, possibly bundled by a build tool like `netlify-lambda` or `tsc`
132. each function as a zip of a folder of files
143. as of [CLI v2.7](https://www.netlify.com/docs/cli/#unbundled-javascript-function-deploys), a non-bundled, non-zipped, folder of files.
15
16`Netlify-Lambda` uses webpack to bundle up your functions and their dependencies for you, suiting the first approach. However, if you have native node modules (or other dependencies that don't expect to be bundled like [the Firebase SDK](https://github.com/netlify/netlify-lambda/issues/112)) then you may want to try the other approaches. In particular, try [`Netlify Dev`](https://github.com/netlify/netlify-dev-plugin#what-is-netlify-dev).
17
18If this sounds confusing, support is available through [our regular channels](https://www.netlify.com/support/).
19</details>
20
21
22<details>
23 <summary><b>Netlify Dev vs. Netlify-Lambda</b></summary>
24
25 ### You can see how to convert a Netlify-Lambda project to Netlify Dev as well as why and how they work together in [this 48 min video here](https://www.youtube.com/watch?v=sakKOT6nkkE)
26
27[`Netlify Dev`](https://github.com/netlify/netlify-dev-plugin#what-is-netlify-dev) is incrementally adoptable. **`netlify-lambda` is still recommended if you need a build step for your functions**, as explained here:
28
29- **When to use Netlify Dev**: Part of Netlify Dev serves unbundled function folders through [zip-it-and-ship-it](https://github.com/netlify/zip-it-and-ship-it) with no build step. This is likely to be attractive to many users who previously just needed `netlify-lambda` for bundling multi-file functions or functions with node_module dependencies.
30- **When to use Netlify Lambda**: However, if you need a build step for your functions (e.g. for webpack import/export syntax, running babel transforms or typescript), you can use `netlify-lambda`, `tsc` or your own build tool to do this, just point Netlify Dev at your build output with the `functions` field in `netlify.toml`.
31- These responsibilities aren't exactly the same. Therefore **you can use Netlify Dev and Netlify Lambda together** to have BOTH a build step for functions from `netlify-lambda` and the full proxy environment from Netlify Dev. If you have a npm script in `package.json` for running `netlify-lambda serve ${functionsSourceFolder}`, Netlify Dev will [detect it](https://github.com/netlify/netlify-dev-plugin#function-builders-function-builder-detection-and-relationship-with-netlify-lambda) and run it for you. This way, **existing `netlify-lambda` users will be able to use Netlify Dev with no change to their workflow**
32
33Function Builder detection is a very new feature with only simple detection logic for now, that we aim to improve over time. If it doesn't work well for you, you can simply not use Netlify Dev for now while we work out all your bug reports. 🙏🏼
34
35</details>
36
37
38
39## Installation
40
41**We recommend installing locally** rather than globally:
42
43```bash
44yarn add netlify-lambda
45```
46
47This will ensure your build scripts don't assume a global install which is better for your CI/CD (for example with Netlify's buildbot).
48
49If you don't have a [`netlify.toml`](https://www.netlify.com/docs/netlify-toml-reference/) file, you'll need one ([example](https://github.com/netlify/create-react-app-lambda/blob/master/netlify.toml)). Define the `functions` field where the functions will be built to and served from, e.g.
50
51```toml
52# example netlify.toml
53[build]
54 command = "yarn build"
55 functions = "lambda" # netlify-lambda reads this
56 publish = "build"
57```
58
59## Usage
60
61We expose two commands:
62
63```
64netlify-lambda serve <folder>
65netlify-lambda build <folder>
66```
67
68At a high level, `netlify-lambda` takes a source folder (e.g. `src/lambda`, specified in your command) and outputs it to a built folder, (e.g. `built-lambda`, specified in your `netlify.toml` file).
69
70The `build` function will run a single build of the functions in the folder.
71
72The `serve` function will start a dev server for the source folder and route requests with a `.netlify/functions/` prefix, with a default port of `9000`:
73
74```
75folder/hello.js -> http://localhost:9000/.netlify/functions/hello
76```
77
78It also watches your files and restarts the dev server on change. Note: if you add a new file you should kill and restart the process to pick up the new file.
79
80**IMPORTANT**:
81
82- You need a [`netlify.toml`](https://www.netlify.com/docs/netlify-toml-reference/) file with a `functions` field.
83- Every function needs to be a top-level js/ts/mjs file. You can have subfolders inside the `netlify-lambda` folder, but those are only for supporting files to be imported by your top level function. Files that end with `.spec.*` or `.test.*` will be ignored so you can [colocate your tests](https://github.com/netlify/netlify-lambda/issues/99).
84- Function signatures follow the [AWS event handler](https://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-handler.html) syntax but must be named `handler`. [We use Node v8](https://www.netlify.com/blog/2018/04/03/node.js-8.10-now-available-in-netlify-functions/) so `async` functions **are** supported ([beware common mistakes](https://serverless.com/blog/common-node8-mistakes-in-lambda/)!). Read [Netlify Functions docs](https://www.netlify.com/docs/functions/#javascript-lambda-functions) for more info.
85- Functions [time out in 10 seconds](https://www.netlify.com/docs/functions/#custom-deployment-options) by default although extensions can be requested. We [try to replicate this locally](https://github.com/netlify/netlify-lambda/pull/116).
86
87<details>
88 <summary><b>Environment variables in build and branch context</b></summary>
89
90Read Netlify's [documentation on environment variables](https://www.netlify.com/docs/continuous-deployment/#build-environment-variables).
91`netlify-lambda` should respect the env variables you supply in `netlify.toml` accordingly (except for deploy previews, which make no sense to locally emulate).
92
93However, this is a [relatively new feature](https://github.com/netlify/netlify-lambda/issues/59), so if you encounter issues, file one.
94
95If you need local-only environment variables that you don't place in `netlify.toml` for security reasons, you can configure webpack to use a `.env` file [like in this example](https://github.com/netlify/netlify-lambda/issues/118).
96
97</details>
98
99 <summary>
100 <b>Lambda function examples</b>
101 </summary>
102 If you are new to writing Lambda functions, this section may help you. Function signatures should conform to one of either two styles. Traditional callback style:
103
104 ```js
105exports.handler = function(event, context, callback) {
106 // your server-side functionality
107 callback(null, {
108 statusCode: 200,
109 body: JSON.stringify({
110 message: `Hello world ${Math.floor(Math.random() * 10)}`
111 })
112 });
113};
114 ```
115
116 or you can use async/await:
117
118 ```js
119export async function handler(event, context) {
120 return {
121 statusCode: 200,
122 body: JSON.stringify({ message: `Hello world ${Math.floor(Math.random() * 10)}` })
123 };
124}
125 ```
126
127 For more Functions examples, check:
128
129 - https://functions-playground.netlify.com/ (introductory)
130 - https://functions.netlify.com/examples/ (our firehose of all functions examples)
131 - the blogposts at the bottom of this README
132
133 </details>
134
135## Using with `create-react-app`, Gatsby, and other development servers
136
137<details>
138<summary><b>Why you need to proxy (for beginners)</b></summary>
139
140`react-scripts` (the underlying library for `create-react-app`) and other popular development servers often set up catchall serving for you; in other words, if you try to request a route that doesn't exist, the dev server will try to serve you `/index.html`. This is problematic when you are trying to hit a local API endpoint like `netlify-lambda` sets up for you - your browser will attempt to parse the `index.html` file as JSON. This is why you may see this error:
141
142`Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0`
143
144If this desribes your situation, then you need to proxy for local development. Read on. Don't worry it's easier than it looks.
145
146</details>
147
148### Proxying for local development
149
150> ⚠️IMPORTANT! PLEASE READ THIS ESPECIALLY IF YOU HAVE CORS ISSUES⚠️
151
152When your function is deployed on Netlify, it will be available at `/.netlify/functions/function-name` for any given deploy context. It is advantageous to proxy the `netlify-lambda serve` development server to the same path on your primary development server.
153
154Say you are running `webpack-serve` on port 8080 and `netlify-lambda serve` on port 9000. Mounting `localhost:9000` to `/.netlify/functions/` on your `webpack-serve` server (`localhost:8080/.netlify/functions/`) will closely replicate what the final production environment will look like during development, and will allow you to assume the same function url path in development and in production.
155
156- If you are using with `create-react-app`, see [netlify/create-react-app-lambda](https://github.com/netlify/create-react-app-lambda/blob/f0e94f1d5a42992a2b894bfeae5b8c039a177dd9/src/setupProxy.js) for an example of how to do this with `create-react-app`. [setupProxy is partially documented in the CRA docs](https://facebook.github.io/create-react-app/docs/proxying-api-requests-in-development#configuring-the-proxy-manually). You can also learn how to do this from scratch in a video: https://www.youtube.com/watch?v=3ldSM98nCHI
157- If you are using Gatsby, see [their Advanced Proxying docs](https://www.gatsbyjs.org/docs/api-proxy/#advanced-proxying). This is implemented in the [JAMstack Hackathon Starter](https://github.com/sw-yx/jamstack-hackathon-starter), and here is an accompanying blogpost: [Turning the Static Dynamic: Gatsby + Netlify Functions + Netlify Identity](https://www.gatsbyjs.org/blog/2018-12-17-turning-the-static-dynamic/).
158- If you are using React-Static, check https://github.com/nozzle/react-static/issues/380.
159- If you are using Nuxt.js, see [this issue for how to proxy](https://github.com/netlify/netlify-lambda/pull/28#issuecomment-439675503).
160- If you are using Vue CLI, you may just use https://github.com/netlify/vue-cli-plugin-netlify-lambda/.
161- If you are using with Angular CLI, see the instructions below.
162
163[Example webpack config](https://github.com/imorente/netlify-functions-example/blob/master/webpack.development.config):
164
165```js
166module.exports = {
167 mode: 'development',
168 devServer: {
169 proxy: {
170 '/.netlify': {
171 target: 'http://localhost:9000',
172 pathRewrite: { '^/.netlify/functions': '' }
173 }
174 }
175 }
176};
177```
178
179<details>
180 <summary>
181 <b>Using with <code>Angular CLI</code></b>
182 </summary>
183
184CORS issues when trying to use netlify-lambdas locally with angular? you need to set up a proxy.
185
186Firstly make sure you are using relative paths in your app to ensure that your app will work locally and on Netlify, example below...
187
188```js
189this.http.get('/.netlify/functions/jokeTypescript');
190```
191
192Then place a `proxy.config.json` file in the root of your project, the contents should look something like...
193
194```json
195{
196 "/.netlify/functions/*": {
197 "target": "http://localhost:9000",
198 "secure": false,
199 "logLevel": "debug",
200 "changeOrigin": true
201 }
202}
203```
204
205- The `key` should match up with the location of your Transpiled `functions` as defined in your `netlify.toml`
206- The `target` should match the port that the lambdas are being served on (:9000 by default)
207
208When you run up your Angular project you need to pass in the proxy config with the flag `--proxy-config` like so...
209
210```bash
211 ng serve --proxy-config proxy.config.json
212```
213
214To make your life easier you can add these to your `scripts` in `package.json`
215
216```json
217 "scripts": {
218 "start": "ng serve --proxy-config proxy.config.json",
219 "build": "ng build --prod --aot && yarn nlb",
220 "nls": "netlify-lambda serve src_functions",
221 "nlb": "netlify-lambda build src_functions"
222 }
223```
224
225Obviously you need to run up `netlify-lambda` & `angular` at the same time.
226
227</details>
228<details>
229 <summary>
230 <b>Using with <code>Next.js</code></b>
231 </summary>
232
233Next.js [doesnt use Webpack Dev Server](https://github.com/zeit/next.js/issues/2281), so you can't modify any config in `next.config.js` to get a proxy to run. However, since the CORS proxy issue only happens in dev mode (Functions are on the same domain when deployed on Netlify) you can run Next.js through a Node server for local development:
234
235```js
236touch server.js
237yarn add -D http-proxy-middleware express
238```
239
240```js
241// server.js
242/* eslint-disable no-console */
243const express = require('express');
244const next = require('next');
245
246const devProxy = {
247 '/.netlify': {
248 target: 'http://localhost:9000',
249 pathRewrite: { '^/.netlify/functions': '' }
250 }
251};
252
253const port = parseInt(process.env.PORT, 10) || 3000;
254const env = process.env.NODE_ENV;
255const dev = env !== 'production';
256const app = next({
257 dir: '.', // base directory where everything is, could move to src later
258 dev
259});
260
261const handle = app.getRequestHandler();
262
263let server;
264app
265 .prepare()
266 .then(() => {
267 server = express();
268
269 // Set up the proxy.
270 if (dev && devProxy) {
271 const proxyMiddleware = require('http-proxy-middleware');
272 Object.keys(devProxy).forEach(function(context) {
273 server.use(proxyMiddleware(context, devProxy[context]));
274 });
275 }
276
277 // Default catch-all handler to allow Next.js to handle all other routes
278 server.all('*', (req, res) => handle(req, res));
279
280 server.listen(port, err => {
281 if (err) {
282 throw err;
283 }
284 console.log(`> Ready on port ${port} [${env}]`);
285 });
286 })
287 .catch(err => {
288 console.log('An error occurred, unable to start the server');
289 console.log(err);
290 });
291
292```
293
294run your server and netlify-lambda at the same time:
295
296```js
297// package.json
298 "scripts": {
299 "start": "cross-env NODE_ENV=dev npm-run-all --parallel start:app start:server",
300 "start:app": "PORT=3000 node server.js",
301 "start:server": "netlify-lambda serve functions"
302 },
303```
304
305and now you can ping Netlify Functions with locally emulated by `netlify-lambda`!
306
307For production deployment, you have two options:
308
309- [using `next export` to do static HTML export](https://nextjs.org/docs/#static-html-export)
310- [using the Next.js 8 `serverless` target option](https://nextjs.org/blog/next-8/#serverless-nextjs) to run your site in a function as well.
311
312Just remember to configure your `netlify.toml` to point to the `Next.js` build folder and your `netlify-lambda` functions folder accordingly.
313
314</details>
315
316## Webpack Configuration
317
318By default the webpack configuration uses `babel-loader` to load all js files. Any `.babelrc` in the directory `netlify-lambda` is run from will be respected. If no `.babelrc` is found, a [few basic settings are used](https://github.com/netlify/netlify-lambda/blob/master/lib/build.js#L11-L15a).
319
320If you need to use additional webpack modules or loaders, you can specify an additional webpack config with the `-c`/`--config` option when running either `serve` or `build`.
321
322For example, have a file with:
323
324```js
325// webpack.functions.js
326module.exports = {
327 optimization: { minimize: false }
328};
329```
330
331Then specify `netlify-lambda serve --config ./webpack.functions.js`. If using VSCode, it is likely that the `sourceMapPathOverrides` have to be adapted for breakpoints to work. Read here for more info on [how to modify the webpack config](https://github.com/netlify/netlify-lambda/issues/64#issuecomment-429625191).
332
333The additional webpack config will be merged into the default config via [webpack-merge's](https://www.npmjs.com/package/webpack-merge) `merge.smart` method.
334
335### Babel configuration
336
337The default webpack configuration uses `babel-loader` with a [few basic settings](https://github.com/netlify/netlify-lambda/blob/master/lib/build.js#L19-L33).
338
339However, if any `.babelrc` is found in the directory `netlify-lambda` is run from, or [folders above it](https://github.com/netlify/netlify-lambda/pull/92) (useful for monorepos), it will be used instead of the default one.
340
341If you need to run different babel versions for your lambda and for your app, [check this issue](https://github.com/netlify/netlify-lambda/issues/34) to override your webpack babel-loader.
342
343### Use with TypeScript
344
345We added `.ts` and `.mjs` support recently - [check here for the PR and usage tips](https://github.com/netlify/netlify-lambda/pull/76).
346
3471. Install `@babel/preset-typescript`
348
349```bash
350npm install --save-dev @babel/preset-typescript
351```
352
353You may also want to add `typescript @types/node @types/aws-lambda`.
354
3552. Create a custom `.babelrc` file:
356
357```diff
358{
359 "presets": [
360 "@babel/preset-typescript",
361 "@babel/preset-env"
362 ],
363 "plugins": [
364 "@babel/plugin-proposal-class-properties",
365 "@babel/plugin-transform-object-assign",
366 "@babel/plugin-proposal-object-rest-spread"
367 ]
368}
369```
370
3713. (Optional) if you have `@types/aws-lambda` installed, your lambda functions can use the community typings for `Handler, Context, Callback`. See the typescript instructions in [create-react-app-lambda](https://github.com/netlify/create-react-app-lambda/blob/master/README.md#typescript) for an example.
372
373Check https://github.com/sw-yx/create-react-app-lambda-typescript for a CRA + Lambda full Typescript experience.
374
375## CLI flags/options
376
377There are additional CLI options:
378
379```bash
380-h --help
381-c --config
382-p --port
383-s --static
384-t --timeout
385```
386
387### --config option
388
389If you need to use additional webpack modules or loaders, you can specify an additional webpack config with the `-c`/`--config` option when running either `serve` or `build`.
390
391For example, have a file with:
392
393```js
394// webpack.functions.js
395module.exports = {
396 optimization: { minimize: false }
397};
398```
399
400Then specify `netlify-lambda serve --config ./webpack.functions.js`.
401
402### --timeout option
403
404(This is for local dev/serving only) The default function timeout is 10 seconds. If you need to adjust this because you have requested extra timeout, pass a timeout number here. Thanks to [@naipath](https://github.com/netlify/netlify-lambda/pull/116) for this feature.
405
406### --port option
407
408The serving port can be changed with the `-p`/`--port` option.
409
410### --static option
411
412If you need an escape hatch and are building your lambda in some way that is incompatible with our build process, you can skip the build with the `-s` or `--static` flag. [More info here](https://github.com/netlify/netlify-lambda/pull/62).
413
414## Netlify Identity
415
416Make sure to [read the docs](https://www.netlify.com/docs/functions/#identity-and-functions) on how Netlify Functions and Netlify Identity work together. Basically you have to make your request with an `authorization` header and a `Bearer` token with your Netlify Identity JWT supplied. You can get this JWT from any of our Identity solutions from [gotrue-js](https://github.com/netlify/gotrue-js) to [netlify-identity-widget](https://github.com/netlify/netlify-identity-widget).
417
418Since for practical purposes we cannot fully emulate Netlify Identity locally, we provide [simple JWT decoding inside the `context` of your function](https://github.com/netlify/netlify-lambda/pull/57). This will give you back the `user` info you need to work with.
419
420Minor note: For the `identity` field, since we are not fully emulating Netlify Identity, we can't give you details on the Identity instance, so we give you [unambiguous strings](https://github.com/netlify/netlify-lambda/blob/master/lib/serve.js#L87) so you know not to rely on it locally: `NETLIFY_LAMBDA_LOCALLY_EMULATED_IDENTITY_URL` and `NETLIFY_LAMBDA_LOCALLY_EMULATED_IDENTITY_TOKEN`. In production, of course, Netlify Functions will give you the correct `identity.url` and `identity.token` fields. We find we dont use this info often in our functions so it is not that big of a deal in our judgment.
421
422## Debugging
423
424To debug lambdas, prepend the `serve` command with [npm's package runner npx](https://medium.com/@maybekatz/introducing-npx-an-npm-package-runner-55f7d4bd282b), e.g. `npx --node-arg=--inspect netlify-lambda serve ...`.
425
4261. make sure that sourcemaps are built along the way (e.g. in the webpack configuration and the `tsconfig.json` if typescript is used)
4272. webpack's minification/uglification is turned off (see below):
428
429For example, to customize the webpack config you can have a file with:
430
431```js
432// webpack.functions.js
433module.exports = {
434 optimization: { minimize: false }
435};
436```
437
438So you can run something like `npx --node-arg=--inspect netlify-lambda serve --config ./webpack.functions.js`. If using VSCode, it is likely that the `sourceMapPathOverrides` have to be adapted for breakpoints to work. Read here for more info on [how to modify the webpack config](https://github.com/netlify/netlify-lambda/issues/64#issuecomment-429625191).
439
440Netlify Functions [run in Node v8.10](https://www.netlify.com/blog/2018/04/03/node.js-8.10-now-available-in-netlify-functions/) and you may need to run the same version to mirror the environment locally. Also make sure to check that you aren't [committing one of these common Node 8 mistakes in Lambda!](https://serverless.com/blog/common-node8-mistakes-in-lambda/)
441
442**Special warning on `node-fetch`**: `node-fetch` and webpack [currently don't work well together](https://github.com/bitinn/node-fetch/issues/450). You will have to use the default export in your code:
443
444```js
445const fetch = require('node-fetch').default // not require('node-fetch')
446```
447
448Don't forget to search our issues in case someone has run into a similar problem you have!
449
450## Example functions and Tutorials
451
452You can do a great deal with lambda functions! Here are some examples for inspiration:
453
454- Basic Netlify Functions tutorial: https://flaviocopes.com/netlify-functions/
455- Netlify's list of Function examples: https://functions-playground.netlify.com/ ([Even more in the README](https://github.com/netlify/functions) as well as our full list https://functions.netlify.com/examples/)
456- Slack Notifications: https://css-tricks.com/forms-auth-and-serverless-functions-on-gatsby-and-netlify/#article-header-id-9
457- URL Shortener: https://www.netlify.com/blog/2018/03/19/create-your-own-url-shortener-with-netlifys-forms-and-functions/
458- Gatsby + Netlify Identity + Functions: [Turning the Static Dynamic: Gatsby + Netlify Functions + Netlify Identity](https://www.gatsbyjs.org/blog/2018-12-17-turning-the-static-dynamic/)
459- Raymond Camden's [Adding Serverless Functions to Your Netlify Static Site](https://www.raymondcamden.com/2019/01/08/adding-serverless-functions-to-your-netlify-static-site)
460- Travis Horn's [Netlify Lambda Functions from Scratch](https://travishorn.com/netlify-lambda-functions-from-scratch-1186f61c659e)
461- [JAMstack with Divya Sasidharan & Phil Hawksworth | Devchat.tv](https://devchat.tv/js-jabber/jsj-347-jamstack-with-divya-sasidharan-phil-hawksworth/) - Great discussion on the problems that Netlify Functions solve
462- [Netlify function error reporting with Sentry](https://httptoolkit.tech/blog/netlify-function-error-reporting-with-sentry/) - automatic error reporting for your Netlify functions, so you know any time they fail.
463- React + Stripe + Netlify Functions: [Build and deploy a serverless eCommerce project](https://mitchgavan.com/react-serverless-shop/)
464- [**Submit your blogpost here!**](https://github.com/netlify/netlify-lambda/issues/new)
465
466These libraries pair very well for extending your functions capability:
467
468- Middleware: https://github.com/middyjs/middy
469- GraphQL: https://www.npmjs.com/package/apollo-server-lambda
470- [Any others to suggest?](https://github.com/netlify/netlify-lambda/issues/new)
471
472## Other community approaches
473
474If you wish to serve the full website from lambda, [check this issue](https://github.com/netlify/netlify-lambda/issues/36).
475
476If you wish to run this server for testing, [check this issue](https://github.com/netlify/netlify-lambda/issues/49).
477
478If you wish to emulate more Netlify functionality locally, check this repo: https://github.com/8eecf0d2/netlify-local. We are considering merging the projects [here](https://github.com/netlify/netlify-lambda/issues/75).
479
480All of the above are community maintained and not officially supported by Netlify.
481
482## Changelog
483
484- v1.0: https://twitter.com/Netlify/status/1050399820484087815 Webpack 4 and Babel 7
485- v1.1: https://twitter.com/swyx/status/1069544181259849729 Typescript support
486- v1.2: https://twitter.com/swyx/status/1083446733374337024 Identity emulation (& others)
487- v1.3: https://github.com/netlify/netlify-lambda/releases/tag/v1.3.0
488- v1.4: New timeout feature https://github.com/netlify/netlify-lambda/pull/116
489
490## License
491
492[MIT](LICENSE)