Search code examples
node.jsamazon-web-servicesredisamazon-cloudfrontamazon-elasticache

How to connect to AWS ElastiCache Cluster from AWS CloudFront using Node.js?


I am new to AWS CloudFront and AWS in general. I have a Next.js (React SSR framework) website which I deployed onto AWS using serverless-nextjs (https://github.com/serverless-nextjs/serverless-next.js). However, I also need some sort of caching for my web app. I decided to use redis ElastiCache from AWS. I created an redis ElastiCache Cluster on the AWS console.

My attempt:

I setup the code for connecting to the redis ElastiCache like this:

import redis from 'redis';
...

export async function getServerSideProps() { // Server side function for Next.js
    const cache = redis.createClient(6379, "{PRIMARY-ENDPOINT-URL-AWS}");
}

and I run the website locally on my PC. However, I get a timeout error from redis: Error: connect ETIMEDOUT.

How would I be able to connect to the redis ElastiCache Cluster from CloudFront and on my local PC?

Screenshot of the redis ElastiCache Cluster window:

redis ElastiCache


Solution

  • You can't connect to ES from outside (i.e. your local workstation) of AWS directly. ES domains are designed to be only accessible from within your resources (e.g. instances) in the same VPC as your ES domain. From docs:

    Elasticache is a service designed to be used internally to your VPC. External access is discouraged due to the latency of Internet traffic and security concerns. However, if external access to Elasticache is required for test or development purposes, it can be done through a VPN.

    The only way to enable connections from outside AWS to your ES is if you establish a VPN connection between home/work network or Direct Connect as explained in AWS docs:

    This scenario is also supported providing there is connectivity between the customers’ VPC and the data center either through VPN or Direct Connect.

    However, for quick, ad-hock setup you can use ssh tunnel between your local workstation and ES domain. This will require some jump/basion EC2 instance which the tunnel will go through.