utilizing Nuxt code in Elixir/Phoenix

Overview

In my previous work, I combined frontend development with nuxt and backend support from elixir/phoenix, along with nginx for reverse proxy.

Looking to enhance the performance of the system, my goal is now to migrate everything to Elixir/Phoenix.

My Goal

The objective is to integrate my existing nuxt code into Elixir/Phoenix seamlessly.

Areas of Uncertainty

I'm unclear on how to retain the routing, server-side rendering, and configurations set in the nuxt.config.js file. I believe if I can make the components globally accessible, I may be able to forego other configurations altogether.

Answer №1

If considering implementing this in a production environment, it is advisable not to do so :). In my perspective, having the phoenix app responsible for the node.js app may not be the best choice. However, if you wish to run both together during development using a single mix phx.server command, then you can proceed by following the steps below.

To start, create a GenServer that will launch the nuxt app and integrate it into the application supervision tree. Specify the path for the package.json file of your nuxt app as the assets_path. Note that this assets_path does not necessarily have to be within your phoenix app itself.


    defmodule NuxtServer do
      use GenServer, restart: :permanent
      require Logger

      def start_link(assets_path, opts \\ []) do
        GenServer.start(__MODULE__, [assets_path], opts)
      end

      def init([assets_path]) do
        # The package.json under the assets folder should have a "nuxt" script defined in the scripts section
        port = Port.open({:spawn, "npm run nuxt"}, [{:cd, assets_path}])
        ref = Port.monitor(port)
        {:ok, %{port: port, ref: ref, assets_path: assets_path}}
      end

      def handle_info({:DOWN, _, :port, _, _}, %{assets_path: assets_path, ref: ref, port: port}) do
        Logger.error("Nuxt server is down, restarting ...")

        Port.close(port)

        Port.demonitor(ref)
        {:ok, state} = init([assets_path])
        {:noreply, state}
      end

      def handle_info({_prot, {:data, msg}}, s) do
        Logger.debug(msg)
        {:noreply, s}
      end

      def handle_info(msg, state), do: super(msg, state)
    end

After setting up the GenServer, you can then proceed with instructions on how to add a reverse proxy in phoenix, such as utilizing this library if you need to access everything through the phoenix http port.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When async/await is employed, the execution does not follow a specific order

I'm curious about the execution of async/await in JavaScript. Here are some example codes: async function firstMethod(){ new Promise((resolve, reject)) => { setTimeout(() => { resolve("test1"); }, 3000); }); } async ...

What is the best way to enable the delete function exclusively for users who are logged in?

I am currently working on implementing a delete function in JavaScript that will remove a MySQL row if and only if it was created by the user who is currently logged in. This means that users cannot delete rows they did not create. Below is the progress I ...

What is the memory allocation for null values in arrays by node.js?

Continuing the discussion from this thread: Do lots of null values in an array pose any harm? I experimented with node.js by doing this: arr=[] arr[1000]=1 arr[1000000000]=2 arr.sort() However, I encountered the following error: FATAL ERROR: JS Alloca ...

Two DIV elements are merging together with a cool zooming effect

As a beginner in using Bootstrap 4, I am working on creating a practice website. While designing the layout, I encountered an issue that seems simple but I can't seem to figure it out. <div id="box-container" class="container-fluid"> &l ...

Dynamic calendar with flexible pricing options displayed within each cell

I've been wracking my brain over this issue for quite some time now, but still can't seem to find a solution! Is there a React Calendar out there that allows for adding prices within the cells? I simply want to show a basic calendar where each c ...

What is the process for sending values to a component?

I am working with a component called MyComponent: export class MyComponent { @Input() active:boolean; constructor() { console.log(this.active); } } In this component, I have declared an Input, and I pass it in as follows: <mycomp ...

Why is it difficult to display data fetched through getJSON?

The test-json.php script retrieves data from the database and converts it into JSON format. <?php $conn = new mysqli("localhost", "root", "xxxx", "guestbook"); $result=$conn->query("select * From lyb limit 2"); echo '['; $i=0; while($row ...

Update button text in real-time using JavaScript

I am currently working on a dropdown list that contains 5 elements displayed inside a button when pressed. I want the button to show a default text "Filter by:" before displaying the selected tab value. Additionally, I need the caret symbol to be visible. ...

Unable to bind to property as it is not recognized as a valid attribute of the selector component

I have a situation where I need to pass a variable from one component to another using @input. Here is my parent component : @Component({ selector: 'aze', templateUrl: './aze.component.html', styleUrls: [('./aze.compo ...

Tips for structuring a news thread with a staggered approach

On my Drupal 8 website, I have set up a newsfeed. How can I display the news items in staggered rows? I would like the first item to align on the left and the second item to be on the right, repeating this pattern for all subsequent items. Currently, I am ...

Padding-left in InfoBox

Currently, I am in the process of developing a map using Google Maps API3 along with the InfoBox extension available at this link I have successfully implemented an overall padding to the Infobox using the following code snippet: var infoOptions = { disa ...

ReferenceError: 'exports' is undefined in the context of Typescript Jest

I'm currently delving into unit testing with jest and encountered an error that looks like this: > npm run unit > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="771f181012374659475947">[email protected]</ ...

Ajax encountered an error while attempting to load the requested resource

jQuery('input').on('click',function(e){ $.getJSON( "/data.json", function(info){ var name = data.name; } ); }); Every time we click, a JSON request is supposed to be made. But unfortunately ...

Using Express-session in the Internet Explorer browser

When configuring the express-session plugin, I follow this setup: var express = require('express'), session = require('express-session'), uuid = require('node-uuid'); var expiration_day = new Date('9/15/2015&apo ...

What steps do I need to take in order to implement a recursive function that keeps track of the history of local variables

Check out this cool function that takes a multi-dimensional array and converts it into a single-dimensional array using recursion. It's pretty nifty because it doesn't use any global variables, so everything is contained within the function itsel ...

Ensuring accuracy within a personalized directive that is implemented numerous times within a single webpage (AngularJS)

Recently, I designed a unique directive that includes various inputs and dropdowns. To ensure proper binding between the outer and inner scopes for two-way data binding, I implemented an isolate scope. This setup allows me to reuse the directive multiple t ...

"AngularJS offers a unique way to include alternative text in placeholders and titles using

I need to implement an input field (<input..>) with a placeholder and title for tooltip that functions in the following way: There is a variable called "myString" which can either be undefined/empty or contain a string. When empty, a default string ...

Uploading files with previews and no option to alter the image dimensions

I am having trouble with resizing an image preview before submitting it. Despite setting the width and height to 1px in both the div and image, it still displays at its normal dimensions. $(function() { var imagesPreview = function(input, placeToIns ...

Display chart labels are constantly visible in Vue Chart JS

In my Vue.js JavaScript application, I am working on setting up a chart where I want the labels and chart information to be visible at all times without requiring mouse hover. Check out this image of the chart. This is the code snippet for my chart: < ...

What is the best way to delete information from a database with the help of Redux

Lately, I've been grappling with the task of integrating redux into my project. Successfully posting data to the database using redux and then retrieving it in react was a win, but now I find myself struggling with how to handle deleting data through ...