Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to turn an node.js express server as an AWS lambda?

I have a full blown node.js express server with many endpoints.

I need to morph this code into an AWS lambda. All the examples I have seen, the express server only exposes one endpoint and it is defined and exported as exports.handler.

Are they hints on how to do this?

like image 794
reza Avatar asked Oct 28 '25 07:10

reza


1 Answers

If I'm understanding you properly you have an express.js app that you would like to run on Lambda?

Claudia.js could help you to deploy your app to AWS Lambda.

Make sure you configured your AWS access credentials before running Claudia commands.

Your code should be slightly modified to support AWS Lambda and deployment via Claudia. You need to export your app instead of starting the server using app.listen. Your app.js should look like the following code listing:

'use strict'
const express = require('express')
const app = express()
app.get('/', (req, res) => res.send('Hello world!'))
module.exports = app

That would break a local Express server, but you can add app.local.js file with the following content:

'use strict'
const app = require('./app')
const port = process.env.PORT || 3000
app.listen(port, () => 
console.log(`Server is listening on port ${port}.`)
)

And then run the local server using the following command:

node app.local.js

To make your app work correctly with AWS Lambda, you need to generate AWS Lambda wrapper for your Express app. With Claudia, you can do so by running the following command in your terminal:

claudia generate-serverless-express-proxy --express-module app

Where app is a name of an entry file of your Express app, just without the .js extension.

This step generated a file named lambda.js, with the following content:

'use strict'
const awsServerlessExpress = require('aws-serverless-express')
const app = require('./app')
const binaryMimeTypes = [
  'application/octet-stream',
  'font/eot',
  'font/opentype',
  'font/otf',
  'image/jpeg',
  'image/png',
  'image/svg+xml'
   ]
    const server = awsServerlessExpress
  .createServer(app, null, binaryMimeTypes)
exports.handler = (event, context) =>
  awsServerlessExpress.proxy(server, event, context
)

Now you only need to deploy your Express app (with lambda.js file) to AWS Lambda and API Gateway using the claudia create command.

claudia create --handler lambda.handler --deploy-proxy-api --region eu-central-1

After a few moments, the command finished and printed the following response:

{
  "lambda": {
    "role": "awesome-serverless-expressjs-app-executor",
    "name": "awesome-serverless-expressjs-app",
    "region": "eu-central-1"
  },
  "api": {
    "id": "iltfb5bke3",
    "url": "https://iltfb5bke3.execute-api.eu-central-1.amazonaws.com/latest"
  }
}
like image 196
svsdnb Avatar answered Oct 30 '25 23:10

svsdnb