Does http-proxy-middleware work with Serverless Lambda? - http

I'm trying to proxy an external API through Serverless Lambda. Trying the following example for the code below: http://localhost:3000/users/1 returns 200 but body is empty. I must be overlooking something as http://localhost:3000/users/11 returns a 404 (as expected).
index.js
'use strict';
const serverless = require('serverless-http');
const express = require('express');
const {
createProxyMiddleware
} = require('http-proxy-middleware');
const app = express();
const jsonPlaceholderProxy = createProxyMiddleware({
target: 'http://jsonplaceholder.typicode.com',
changeOrigin: true,
logLevel: 'debug'
});
app.use('/users', jsonPlaceholderProxy);
app.get('/', (req, res) => {
res.json({
msg: 'Hello from Serverless!'
})
})
const handler = serverless(app);
module.exports.handler = async (event, context) => {
try {
const result = await handler(event, context);
return result;
} catch (error) {
return error;
}
};
serverless.yml
service: sls-proxy-test
provider:
name: aws
runtime: nodejs12.x
plugins:
- serverless-offline
functions:
app:
handler: index.handler
events:
- http:
method: ANY
path: /
- http: "ANY {proxy+}"
package.json
{
"name": "proxy",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"sls": "sls",
"offline": "sls offline start"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"express": "4.17.1",
"http-proxy-middleware": "1.0.1",
"serverless-http": "2.3.2"
},
"devDependencies": {
"serverless": "1.65.0",
"serverless-offline": "5.12.1"
}
}

try to remove the transfer-encoding header from the response in onProxyRes listener inside createProxyMiddleware
const jsonPlaceholderProxy = createProxyMiddleware({
onProxyRes: function (proxyRes, req, res) { // listener on response
delete proxyRes.headers['transfer-encoding']; // remove header from response
},
// remaining code

I had the same issue but adding the below onProxyRes option solved it
onProxyRes(proxyRes, req, res) {
const bodyChunks = [];
proxyRes.on('data', (chunk) => {
bodyChunks.push(chunk);
});
proxyRes.on('end', () => {
const body = Buffer.concat(bodyChunks);
res.status(proxyRes.statusCode);
Object.keys(proxyRes.headers).forEach((key) => {
res.append(key, proxyRes.headers[key]);
});
res.send(body);
res.end();
});
}

Related

Apollo Client is not working with NextJS using SSR

I'm trying to use Apollo Client/Server for my NextJS, and some pages I'm trying to SSR and staticlly generate them, but I'm faing an issue with Apollo where it fails to fetch on server but not when I use the client on the client.
Firstlly this is my package json, where my libs are configed:
{
"name": "landing",
"version": "1.0.0",
"private": true,
"scripts": {
"dev": "next dev -p 9999",
"build": "next build",
"start": "next start -p 9999",
"lint": "next lint"
},
"dependencies": {
"#apollo/react-hooks": "^4.0.0",
"#reduxjs/toolkit": "^1.9.0",
"apollo-server-micro": "2.25.1",
"deepmerge": "^4.2.2",
"firebase": "^9.14.0",
"graphql": "^15.5.1",
"loadash": "^1.0.0",
"luxon": "^3.1.1",
"mongoose": "^5.13.15",
"next": "11.0.1",
"next-redux-wrapper": "^8.0.0",
"react": "17.0.2",
"react-dom": "17.0.2",
"react-images-uploading": "^3.1.7",
"react-infinite-scroll-component": "^6.1.0",
"react-redux": "^8.0.5",
"react-tag-input-component": "^2.0.2",
"uuid": "^9.0.0"
},
"devDependencies": {
"autoprefixer": "^10.4.13",
"eslint": "7.32.0",
"eslint-config-next": "11.0.1",
"postcss": "^8.4.19"
}
}
And here is my single API route in pages/api.jsx folder:
import { Connect } from "../utils/Connect";
import { ApolloServer, makeExecutableSchema } from "apollo-server-micro";
import { defs as typeDefs } from "../graphql/defs";
import { resolves as resolvers } from "../graphql/resolves";
Connect();
export const schema = makeExecutableSchema({ typeDefs, resolvers });
const api = { bodyParser: false };
const path = { path: "/api" };
export const config = { api };
export default new ApolloServer({ schema }).createHandler(path);
While this is my Mongo Connection that I imported earlier:
import mongoose from "mongoose";
export const Connect = async () => {
try {
await mongoose.connect(process.env.MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
useCreateIndex: true,
});
} catch (err) {
console.log(`Something went wrong trying to connect to the database);
process.exit(1);
}
};
While this is my Apollo Client which is configured for Client and Server calls:
import merge from "deepmerge";
import { useMemo } from "react";
import { ApolloClient, HttpLink, InMemoryCache, from } from "#apollo/client";
import { onError } from "#apollo/client/link/error";
import { concatPagination } from "#apollo/client/utilities";
import { isEqual } from "lodash";
export const APOLLO_STATE_PROP_NAME = "__APOLLO_STATE__";
let apolloClient;
const errorLink = onError(({ graphQLErrors, networkError }) => {
if (graphQLErrors) graphQLErrors.forEach(({ message, locations, path }) => {
const msg = `[GraphQL error]: Message: ${message}`;
const lct = `Location: ${locations}`;
const pth = `Path: ${path}`;
console.log(`${msg}, ${lct}, ${pth}`);
});
if (networkError) {
const ntw = `[Network error]: ${networkError}`;
console.log(ntw);
}
});
const httpLink = new HttpLink({
uri: `http://localhost:9999/api`,
credentials: "same-origin",
});
function createApolloClient() {
return new ApolloClient({
ssrMode: typeof window === "undefined",
link: from([errorLink, httpLink]),
cache: new InMemoryCache({
typePolicies: {
Query: {
fields: {
allPosts: concatPagination(),
},
},
},
}),
});
}
export function initializeApollo(initialState = null) {
const _apolloClient = apolloClient ?? createApolloClient();
if (initialState) {
const existingCache = _apolloClient.extract();
const data = merge(existingCache, initialState, {
arrayMerge: (destinationArray, sourceArray) => [
...sourceArray,
...destinationArray.filter((d) =>
sourceArray.every((s) => !isEqual(d, s))
),
],
});
_apolloClient.cache.restore(data);
}
if (typeof window === "undefined") return _apolloClient;
if (!apolloClient) apolloClient = _apolloClient;
return _apolloClient;
}
export function addApolloState(client, pageProps) {
if (pageProps?.props) pageProps.props[APOLLO_STATE_PROP_NAME] = client.cache.extract();
return pageProps;
}
export function useApollo(pageProps) {
const state = pageProps[APOLLO_STATE_PROP_NAME];
const store = useMemo(() => initializeApollo(state), [state]);
return store;
}
And lately, this is my page that is SSR-ing:
import { Category } from "../../ui/pages";
import { addApolloState, initializeApollo } from "../../config/Apollo";
import { Description, Globals, Title } from "../../config/Metas";
import { CATEGORIES, CATEGORY } from "../../graphql/queries";
export async function getStaticPaths() {
let paths = [];
const Apollo = initializeApollo();
const config = { query: CATEGORIES };
const categories = await Apollo.query(config);
paths = categories.data.Categories.map((category) => {
return {
params: {
category: category.Name.toLowerCase(),
...category,
},
};
});
return {
paths,
fallback: false,
};
}
export async function getStaticProps(context) {
const Apollo = initializeApollo();
const slug = context.params.category;
const category = await Apollo.query({
query: CATEGORY,
variables: { slug },
});
if (category) {
const data = { props: { category } };
return addApolloState(Apollo, data);
}
else return {
notFound: true,
};
}
const Route = ({ category }) => {
const { data } = category;
const { Category: Meta } = data;
return (
<>
<Globals />
<Title title={Meta.Name} />
<Description description={Meta.Description} />
<Category />
</>
);
};
export default Route;
All those queries that I call are being tested on the Apollo client on front and they are working, but when I do this and start the server with npm run dev I get a weird error:
[Network error]: TypeError: fetch failed
Error [ApolloError]: fetch failed
at new ApolloError (/Users/bfzli/Code/landdding/node_modules/#apollo/client/errors/errors.cjs:34:28)
at /Users/bf/Code/landing/node_modules/#apollo/client/core/core.cjs:1800:19
at both (/Users/bf/Code/landing/node_modules/#apollo/client/utilities/utilities.cjs:997:53)
at /Users/bf/Code/landing/node_modules/#apollo/client/utilities/utilities.cjs:990:72
at new Promise (<anonymous>)
at Object.then (/Users/bf/Code/landing/node_modules/#apollo/client/utilities/utilities.cjs:990:24)
at Object.error (/Users/bf/Code/landing/node_modules/#apollo/client/utilities/utilities.cjs:998:49)
at notifySubscription (/Users/bf/Code/landing/node_modules/zen-observable/lib/Observable.js:140:18)
at onNotify (/Users/bf/Code/landing/node_modules/zen-observable/lib/Observable.js:179:3)
at SubscriptionObserver.error (/Users/bf/Code/landing/node_modules/zen-observable/lib/Observable.js:240:7) {
type: 'ApolloError',
graphQLErrors: [],
clientErrors: [],
networkError: {
cause: {
errno: -61,
code: 'ECONNREFUSED',
syscall: 'connect',
address: '::1',
port: 9999
}
}
}

Nextjs How to send Etag thorugh vercel?

I want to send Etag.
export const getServerSideProps: GetServerSideProps = async ({ req, res }) => {
const targetIndex =
req.rawHeaders.findIndex((val) => val === "If-None-Match") + 1;
const EtagVal = req.rawHeaders[targetIndex];
res.setHeader("Cache-Control", "public, max-age=0, must-revalidate");
res.setHeader("ETag", "aaaa");
return {
props: {},
};
};
This Works locally. build & next start..
It does not work after vercel deployment.
I tried configure next.config.js like this
const nextConfig = {
reactStrictMode: true,
async headers() {
return [
{
source: '/:path*',
"headers" : [
{
"key" : "ETag",
},
{
"key" : "If-None-Match",
}
]
}
]
}
}
Unlike the document that any value is allowed if value is not defined,
An error occurs during the build phase.

Problem Using Stripe Payment In React Native App

I am using stripe in React Native App not expo and using .Net Core web api as a backend,
this is my backend code where, stripe customers creates and their ephemeral keys and setup_intent
public Customer create_customer()
{
StripeConfiguration.ApiKey =_appSettings.StripeApiSecret;
var options = new CustomerCreateOptions
{
Description = "My First Test Customer",
};
var service = new CustomerService();
return service.Create(options);
}
public EphemeralKey create_empherical_key(string customerId)
{
var options = new EphemeralKeyCreateOptions
{
StripeVersion = "2020-08-27",
Customer = customerId
};
var service = new EphemeralKeyService();
return service.Create(options);
}
public SetupIntent setup_intent(string customerId)
{
var options = new SetupIntentCreateOptions
{
Customer = customerId
};
var service = new SetupIntentService();
return service.Create(options);
}
my backend is working fine it creates all the values that stripe needs,
main problem is lying here in React Native app
function CheckoutScreen() {
const { initPaymentSheet, presentPaymentSheet } = useStripe();
const [loading, setLoading] = useState(false);
const fetchPaymentSheetParams = async () => {
const response = await fetch(`${ environment.stripeurl +`create_customer`}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
});
const { setupIntent, ephemeralKey, customer } = await response.json();
return {
setupIntent,
ephemeralKey,
customer,
};
};
const initializePaymentSheet = async () => {
const {
setupIntent,
ephemeralKey,
customer,
} = await fetchPaymentSheetParams();
const { error } = await initPaymentSheet({
customerId: customer.id,
customerEphemeralKeySecret: ephemeralKey.secret,
setupIntentClientSecret: setupIntent.clientSecret,
});
if (!error) {
setLoading(true);
}
};
const openPaymentSheet = async () => {
const { error } = await presentPaymentSheet();
if (error) {
Alert.alert(`Error code: ${error.code}`, error.message);
} else {
Alert.alert('Success', 'Your payment method is successfully set up for future payments!');
}
};
useEffect(() => {
initializePaymentSheet();
}, []);
return (
<View>
<Button
variant="primary"
disabled={!loading}
title="Set up"
onPress={openPaymentSheet}
/>
</View>
);
I receiving all the values of customer, setupintent and ephemeralkey in the front end, when it reach on the line
const { error } = await presentPaymentSheet();
the app crashes.
for refrence I am also providing link of the documentation.
https://stripe.com/docs/payments/save-and-reuse?platform=react-native&ui=payment-sheet
And these are the packages version that I am currently using in this react-native app.
{
"name": "Tookan_App",
"version": "0.0.1",
"private": true,
"scripts": {
"android": "react-native run-android",
"ios": "react-native run-ios",
"start": "react-native start",
"test": "jest",
"lint": "eslint ."
},
"dependencies": {
"#stripe/stripe-react-native": "^0.12.0",
"react": "17.0.2",
"react-native": "0.68.2"
},
"devDependencies": {
"#babel/core": "^7.18.2",
"#babel/runtime": "^7.18.3",
"#react-native-community/eslint-config": "^3.0.2",
"babel-jest": "^28.1.0",
"eslint": "^8.16.0",
"jest": "^28.1.0",
"metro-react-native-babel-preset": "^0.71.0",
"react-test-renderer": "17.0.2"
},
"jest": {
"preset": "react-native"
}
}

Problem with nuxt (SSR) and firestore rules

I use Nuxt (universal mode) with Firestore, I set rules properly but I still get this error:
I get Missing or insufficient permissions
when I reload the page. When ccessing the page through the router, I don't get any error, the rules re working as it's supposed to.
Firestore is called in the asyncData (as it's a SSR app).
If I check the req.user in asynData when loading the page, everything looks fine. I have the roles and all information. It seems that serverMiddleware is activated after the asyncData, when reloading the browser. Any ideas why?
My Firestore rules:
service cloud.firestore {
match /databases/{database}/documents {
function isApplicant() {
return request.auth.token.roles.applicant == true
}
match /tests/{test} {
allow read: if isApplicant();
}
}
}
serverMiddleware:
const admin = require('../services/firebase-admin-init.js')
const cookieParser = require('cookie-parser')();
global.XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest
module.exports = async function (req, res, next) {
await getIdTokenFromRequest(req, res).then(idToken => {
if (idToken) {
addDecodedIdTokenToRequest(idToken, req).then(() => {
next();
});
} else {
next();
}
});
}
function getIdTokenFromRequest(req, res) {
if (req.headers.authorization && req.headers.authorization.startsWith('Bearer ')) {
return Promise.resolve(req.headers.authorization.split('Bearer ')[1]);
}
return new Promise(function(resolve) {
cookieParser(req, res, () => {
if (req.cookies && req.cookies.__session) {
console.log("new")
console.log('Found "__session" cookie');
// Read the ID Token from cookie.
resolve(req.cookies.__session);
} else {
resolve();
}
});
});
}
/**
* Returns a Promise with the Decoded ID Token and adds it to req.user.
*/
function addDecodedIdTokenToRequest(idToken, req) {
// console.log('Start addDecodedIdTokenToRequest')
return admin.auth().verifyIdToken(idToken).then(decodedIdToken => {
console.log('ID Token correctly decoded', decodedIdToken);
req.user = decodedIdToken;
}).catch(error => {
console.error('Error while verifying Firebase ID token:', error);
});
}
Nuxt config files:
const path = require('path');
const environment = process.env.NODE_ENV || 'development';
const envSet = require(`./config/env.${environment}.js`);
module.exports = {
env: envSet,
mode: 'universal',
plugins: [
{ src: '~/plugins/fireinit.js', ssr: false, },
{ src: '~/plugins/auth-cookie.js', ssr: false },
{ src: '~/plugins/fireauth.js', ssr: false }
],
router: {
},
serverMiddleware: [
'~/serverMiddleware/validateFirebaseIdToken'
],
modules: [
'vue-scrollto/nuxt',
['nuxt-validate', {
lang: 'ja'
}],
'#nuxtjs/axios',
],
css: [
{src: '~/assets/scss/app.scss', lang: 'scss'}
],
/*
** Customize the progress bar color
*/
loading: { color: '#403a8f' },
resolve: {
extensions: ['.js', '.json', '.vue', '.ts'],
root: path.resolve(__dirname),
alias: {
'~': path.resolve(__dirname),
'#': path.resolve(__dirname)
},
},
/*
** Build configuration
*/
buildDir: '../cloud/front/',
build: {
publicPath: '/assets/',
extractCSS: true,
quiet: false,
terser: {
terserOptions: {
compress: {
drop_console: environment === 'production' ? true : false,
},
},
},
},
}

How actionssdk cloud functions is working

index.js file
'use strict';
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const {actionssdk} = require('actions-on-google');
const app = actionssdk({debug: true});
// // Create and Deploy Your First Cloud Functions
// // https://firebase.google.com/docs/functions/write-firebase-functions
//
app.intent('actions.intent.MAIN', function (conv, input) {
conv.ask('<speak>Hi! <break time="1"/> ' +
'You are entering into samplejs5 application by typing ' +
("<say-as >" + input + "</say-as>.</speak>"));
});
const getUser = functions.https.onRequest((req, res) => {
console.log("req.params.uid--------->",req.params.uid)
const uid = req.params.uid;
/*const doc = admin.firestore().doc(`users/${uid}`)
doc.get().then(snapshot => {
res.send(snapshot.data())
}).catch(error => {
res.status(500).send(error)
})*/
})
exports.dairyProduct = functions.https.onRequest(app);
Action.json
{
"actions": [
{
"description": "Default Welcome Intent",
"name": "MAIN",
"fulfillment": {
"conversationName": "testapp"
},
"intent": {
"name": "actions.intent.MAIN",
"trigger": {
"queryPatterns": [
"Talk to Dairy Product"
]
}
}
}
],
"conversations": {
"testapp": {
"name": "testapp",
"url": "https://us-central1-samplejs6-id.cloudfunctions.net/dairyProduct",
"fulfillmentApiVersion": 2,
"inDialogIntents": [
{
"name": "actions.intent.CANCEL"
}
]
}
},
"locale": "en"
}
I am new to actionsdk, I want to get userUID, Since i am using dairyProduct function, how to call getUser? what would be the value of UID,
Please share the guide for creating user, and end user authentication with sample, how they are calling the functions
For calling main intent, we have to type talk to test app, Once main Intent is called, how to authenticate the user

Resources