bldg14 / eventual

A simple event calendar
https://eventual-client.fly.dev
MIT License
0 stars 0 forks source link

link frontend and backend in production #43

Closed kevinfalting closed 10 months ago

kevinfalting commented 11 months ago

Issue Description

In an earlier issue, I managed to link the two together for local development https://github.com/bldg14/eventual/pull/17, and I had made an assumption about how I might make that work:

The assumption is that in production we'll be serving the client from the some origin as the server. A problem left for later.

This is no longer the case. Without having control of the reverse proxy to direct some of the paths to a different server, my plan is to use a subdomain for the server, effectively a different domain than the client. Using a subdomain for the server should make some security problems simpler.

According to the create-react-app docs, environment variables are embedded during the build time and looks for environment variables prefixed with REACT_APP_. These must not be secrets since they get embedded into the build and served, easily inspectable.

As an example of this:

REACT_APP_BACKEND_URL=http://your-production-backend.domain.com

Then in the client, it can be referenced via

const backendUrl = process.env.REACT_APP_BACKEND_URL;

We'll have to ensure that these environment variables are set during build time though.

Supporting Documentation

Implementation Details

This is going to require the implementation of some client side code, which will be useful later on. I'll create an http directory to export from.

const baseUrl = process.env.REACT_APP_BACKEND_URL;

export const get = async (endpoint: string, queryParameters?: Record<string, string>): Promise<any> => {
    const queryString = queryParameters ? new URLSearchParams(queryParameters).toString() : '';
    const url = queryString ? `${baseUrl}${endpoint}?${queryString}` : `${baseUrl}${endpoint}`;

    const headers = {
        "Content-Type": "application/json",
    };

    const config: RequestInit = {
        method: "GET",
        headers,
    };

    let response;
    try {
        response = await fetch(url, config);
        if (!response.ok) {
            throw new Error(String(response.status));
        }
    } catch (error) {
        throw new Error(`Fetching ${url} failed: ${error}`);
    }

    return response.json();
};

Acceptance Criteria

kevinfalting commented 11 months ago

The resulting PR from this issue will resolve both this issue and https://github.com/bldg14/eventual/issues/18.