Two NextJS applications in separate repositories under one backend

I have two NextJS applications under separate repositories and different domains.

I want the second NextJS application to fetch the first NextJS application’s backend code. Backend is graphql + apollo. But I am reaching a “Access-Control-Allow-Origin” problem since they have mismatching domains.

Here is a diagram to illustrate my setup. What are the best practices to tackle this issue? Two UIs, two domains, one backend.

On localhost, it works well.

Application A: localhost:3000
Application B: localhost:4000

For application B, NEXT_PUBLIC_APOLLO_BASE_URL is “localhost:3000”. But when it switches to the hosted domain, CORS issues arise

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import {
ApolloClient,
ApolloClientOptions,
InMemoryCache,
NormalizedCacheObject,
createHttpLink,
} from '@apollo/client'
import { auth } from 'app/firebase/clientApp'
import { setContext } from '@apollo/client/link/context'
//import { offsetLimitPagination } from "@apollo/client/utilities";
//
//
const apolloCache = new InMemoryCache({
typePolicies: {
SearchConfigOption: {
keyFields: ['pathName'],
},
Query: {
fields: {
/* filterItems: {
keyArgs: ['user'],
merge(existing, incoming) {
if (!incoming) return existing
if (!existing) return incoming // existing will be empty the first time
const { items, ...rest } = incoming
let result = rest
result.items = [...existing.items, ...items] // Merge existing items with the items from incoming
return result
},
},*/
},
},
},
})
const httpLink = createHttpLink({
uri: `${process.env.NEXT_PUBLIC_APOLLO_BASE_URL}api/graphql`,
credentials: 'include',
})
const authLink = setContext(async (_, { headers }) => {
const user = auth.currentUser
const token = user && (await user.getIdToken())
const modifiedHeader = {
headers: {
...headers,
authorization: token ? `Bearer ${token}` : 'Bearer null',
},
}
return modifiedHeader
})
const client = new ApolloClient({
ssrMode: typeof window === 'undefined',
link: authLink.concat(httpLink),
cache: apolloCache,
connectToDevTools: process.env.NODE_ENV !== 'production',
credentials: 'include',
})
export default client
</code>
<code>import { ApolloClient, ApolloClientOptions, InMemoryCache, NormalizedCacheObject, createHttpLink, } from '@apollo/client' import { auth } from 'app/firebase/clientApp' import { setContext } from '@apollo/client/link/context' //import { offsetLimitPagination } from "@apollo/client/utilities"; // // const apolloCache = new InMemoryCache({ typePolicies: { SearchConfigOption: { keyFields: ['pathName'], }, Query: { fields: { /* filterItems: { keyArgs: ['user'], merge(existing, incoming) { if (!incoming) return existing if (!existing) return incoming // existing will be empty the first time const { items, ...rest } = incoming let result = rest result.items = [...existing.items, ...items] // Merge existing items with the items from incoming return result }, },*/ }, }, }, }) const httpLink = createHttpLink({ uri: `${process.env.NEXT_PUBLIC_APOLLO_BASE_URL}api/graphql`, credentials: 'include', }) const authLink = setContext(async (_, { headers }) => { const user = auth.currentUser const token = user && (await user.getIdToken()) const modifiedHeader = { headers: { ...headers, authorization: token ? `Bearer ${token}` : 'Bearer null', }, } return modifiedHeader }) const client = new ApolloClient({ ssrMode: typeof window === 'undefined', link: authLink.concat(httpLink), cache: apolloCache, connectToDevTools: process.env.NODE_ENV !== 'production', credentials: 'include', }) export default client </code>
import {
  ApolloClient,
  ApolloClientOptions,
  InMemoryCache,
  NormalizedCacheObject,
  createHttpLink,
} from '@apollo/client'
import { auth } from 'app/firebase/clientApp'
import { setContext } from '@apollo/client/link/context'
//import { offsetLimitPagination } from "@apollo/client/utilities";
//
//
const apolloCache = new InMemoryCache({
  typePolicies: {
    SearchConfigOption: {
      keyFields: ['pathName'],
    },
    Query: {
      fields: {
        /* filterItems: {
          keyArgs: ['user'],
          merge(existing, incoming) {
            if (!incoming) return existing
            if (!existing) return incoming // existing will be empty the first time

            const { items, ...rest } = incoming

            let result = rest
            result.items = [...existing.items, ...items] // Merge existing items with the items from incoming

            return result
          },
        },*/
      },
    },
  },
})

const httpLink = createHttpLink({
  uri: `${process.env.NEXT_PUBLIC_APOLLO_BASE_URL}api/graphql`,
  credentials: 'include',
})

const authLink = setContext(async (_, { headers }) => {
  const user = auth.currentUser
  const token = user && (await user.getIdToken())
  const modifiedHeader = {
    headers: {
      ...headers,
      authorization: token ? `Bearer ${token}` : 'Bearer null',
    },
  }
  return modifiedHeader
})

const client = new ApolloClient({
  ssrMode: typeof window === 'undefined',
  link: authLink.concat(httpLink),
  cache: apolloCache,
  connectToDevTools: process.env.NODE_ENV !== 'production',
  credentials: 'include',
})

export default client

The Issue here is that you have to configure the domain of application B in the backend CORS middleware, if you’re using an express server for your backend, this is how you would configure it

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>
const express = require('express');
const cors = require('cors');
const { ApolloServer } = require('apollo-server-express');
const app = express();
const corsOptions = {
origin: ['https://merchant-domain.com', "https://application-2-domain.com"],
credentials: true,
};
app.use(cors(corsOptions));
const server = new ApolloServer({
// Apollo server configuration
});
server.applyMiddleware({ app, path: '/api/graphql', cors: false });
app.listen({ port: 3000 }, () =>
console.log(`Server ready at http://localhost:3000${server.graphqlPath}`)
);
</code>
<code> const express = require('express'); const cors = require('cors'); const { ApolloServer } = require('apollo-server-express'); const app = express(); const corsOptions = { origin: ['https://merchant-domain.com', "https://application-2-domain.com"], credentials: true, }; app.use(cors(corsOptions)); const server = new ApolloServer({ // Apollo server configuration }); server.applyMiddleware({ app, path: '/api/graphql', cors: false }); app.listen({ port: 3000 }, () => console.log(`Server ready at http://localhost:3000${server.graphqlPath}`) ); </code>

const express = require('express');
const cors = require('cors');
const { ApolloServer } = require('apollo-server-express');

const app = express();

const corsOptions = {
  origin: ['https://merchant-domain.com', "https://application-2-domain.com"],
  credentials: true,
};

app.use(cors(corsOptions));

const server = new ApolloServer({
  // Apollo server configuration
});

server.applyMiddleware({ app, path: '/api/graphql', cors: false });

app.listen({ port: 3000 }, () =>
  console.log(`Server ready at http://localhost:3000${server.graphqlPath}`)
);


Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật