Skip to content

Instantly share code, notes, and snippets.

@ctrlShiftBryan
Last active August 2, 2021 02:04
Show Gist options
  • Save ctrlShiftBryan/9343157595808a7857242391ba3de87e to your computer and use it in GitHub Desktop.
Save ctrlShiftBryan/9343157595808a7857242391ba3de87e to your computer and use it in GitHub Desktop.
Phoenix and a traditional front end.

I’m using it with a phoenix backend and a create react app front-end.

This requires building the assets and copying to the priv/static folder. Phoenix acts as a giant file server and then I also use it as an api with graphql absinthe.

Building assets

I make copying to the priv/static folder part of my asset build process package.json build script

    “build”: “rescripts build”,
    “postbuild”: “mkdirp ../priv/static && cpx \“./build/**\” \“../priv/static\” --clean && cpx \“src/styles/tailwind.css\” \“../priv/static\” “,

Phoneix

The phoenix router/controller to serve the file. Router

  scope “/”, AppWeb do
    pipe_through :static
    get “/*path”, PageController, :index
  end

Controller

defmodule AppWeb.PageController do
  use AppWeb, :controller

  def index(conn, _params) do
    path = :code.priv_dir(:app_web)

    # I use string replace to put a few small peices of dynamic info into the html at runtime.

    ga_code = Application.get_env(:app_web, :google_analytics)
    user_id = conn.assigns.user_id

    {:ok, version} = :application.get_key(:app_web, :vsn)

    index_html =
      “#{path}/static/index.html”
      |> File.read!()
      |> String.replace(“UA-00000000-0", ga_code)
      |> String.replace(“local_dev_user”, “#{user_id}“)
      |> String.replace(“replace_gm_version”, version |> to_string())

    html(conn, index_html)
  end
end

Development

For Developement I take advantage of webpack dev servers proxy capabilties. I can use localhost:3000 and run webpack dev server. So you need to run yarn start (port 3000) and iex -S mix phx.server (port 4000) and then webpack dev server proxies api calls. proxy host

  “proxy”: “http://localhost:4000”
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment