Mapping Monorepo To Localized Subdomains

22 views Asked by At

I recently came across an issue in my application regarding sending cookies when the frontend and backend are on different ports. So I mapped some subdomains in my hosts file as such:

//Hosts file

127.0.0.1 development.test.com
::1 development.test.com

127.0.0.1 api.test.com
::1 api.test.com

My frontend is running on localhost:3000 normally with my server on localhost:4000.

I've also got rewrites setup from my nextjs app router frontend to my express backend like so:

//next.config.js

/** @type {import('next').NextConfig} */

const path = require('path')
const API_URL = process.env.API_URL ?? 'http://localhost.com:4000'

const nextConfig = {
  async rewrites() {
    return [{
      source: '/api/:path*',
      destination: `${API_URL}/:path*`,
    }]
  },
  sassOptions: {
    includePaths: [path.join(__dirname, 'styles')],
  }
}

module.exports = nextConfig

//serverSideApi.js - ky wrapper

import ky from "ky"
import { cookies } from "next/headers"

const cookieStore = cookies()

export const serverSideApi = ky.extend({
  prefixUrl: `${process.env.CLIENT_URL ?? "http://localhost:3000"}/api`,
  credentials: "include",
  headers: {
    cookie: cookieStore.toString()
  },
  cache: "no-store"
})

//Index.js file for server

const { exit } = require('node:process')
const { createApp } = require('./app')
const database = require('./database')
const { isDev } = require('./is-dev')

async function main (port = process.env.PORT ?? 4000) {
  console.log('Starting server...')
  // This should only be done on dev btw
  await database.sync()

  const app = createApp()

  app.listen(port, (error) => {
    if (error) return handleFatal(error)
    console.log(`Running on port ${port}, dev: ${isDev()}`)
  })

}

main().catch(handleFatal)

function handleFatal (error) {
  console.error(error)
  exit(1)
}

Im not really sure how to change these files (And maybe my package.json scripts too?) to work with my new subdomains ive created.

Ive tried the obvious but it my turbo just tells me I cant run two on the same port.

Many thanks in advance!

0

There are 0 answers