Git Product home page Git Product logo

inertiajs-adonisjs's Introduction

Inertia.js AdonisJS Provider

Typescript code style: prettier

What is this all about?

Inertia.js lets you quickly build modern single-page React, Vue and Svelte apps using classic server-side routing and controllers.

AdonisJS is a fully featured web framework focused on productivity and developer ergonomics.

Project goals

  • Feature parity with the official Inertia backend adapters
  • Full compatibility with all official client-side adapters
  • Easy setup
  • Quality documentation

Installation

# NPM
npm i @eidellev/inertia-adonisjs

# or Yarn
yarn add @eidellev/inertia-adonisjs

Required AdonisJS libraries

This library depends on two AdonisJS core libraries: @adonisjs/view and @adonisjs/session. If you started off with the api or slim project structure you will need to install these separately:

# NPM
npm i @adonisjs/view
npm i @adonisjs/session

# or Yarn
yarn add @adonisjs/view
yarn add @adonisjs/session

# Additionally, you will need to configure the packages:
node ace configure @adonisjs/view
node ace configure @adonisjs/session

Setup

You can register the package, generate additional files and install additional dependencies by running:

node ace configure @eidellev/inertia-adonisjs

Inertia will query you on your preferences (e.g. which front-end framework you prefer and if you want server side rendering) and generate additional files.

Invoke example

Configuration

The configuration for inertia-adonisjs is set in /config/inertia.ts:

import { InertiaConfig } from '@ioc:EidelLev/Inertia';

export const inertia: InertiaConfig = {
  view: 'app',
};

Register inertia middleware

Add Inertia middleware to start/kernel.ts:

Server.middleware.register([
  () => import('@ioc:Adonis/Core/BodyParser'),
  () => import('@ioc:EidelLev/Inertia/Middleware'),
]);

Making an Inertia Response

export default class UsersController {
  public async index({ inertia, request }: HttpContextContract) {
    const users = await User.all();

    return inertia.render('Users/IndexPage', { users });
  }
}

Making lazy Inertia Response

Lazy responses are useful when you want to render a page without some data that should be loaded initially.

import Inertia from '@ioc:EidelLev/Inertia';

export default class UsersController {
  public async index({ inertia, request }: HttpContextContract) {
    const users = await User.all();

    return inertia.render('Users/IndexPage', {
      users,
      lazyProp: Inertia.lazy(() => {
        return { lazy: 'too lazy' };
      }),
    });
  }
}

The data will be loaded on demand by the explicit Inertia visit with option

{
  only: ['lazyProp'];
}

Root template data

There are situations where you may want to access your prop data in your root Edge template. For example, you may want to add a meta description tag, Twitter card meta tags, or Facebook Open Graph meta tags.

<meta name="twitter:title" content="{{ page.title }}">

Sometimes you may even want to provide data that will not be sent to your JavaScript component.

return inertia.render('Users/IndexPage', { users }, {  metadata: '...' : '...' });

Shared data

Sometimes you need to access certain data on numerous pages within your application. For example, a common use-case for this is showing the current user in the site header. Passing this data manually in each response isn't practical. In these situations shared data can be useful.

In order to add shared props, edit start/inertia.ts:

import Inertia from '@ioc:EidelLev/Inertia';

Inertia.share({
  errors: (ctx) => {
    return ctx.session.flashMessages.get('errors');
  },
  // Add more shared props here
});

Sharing route params

Traditionally in Adonis, we have access to the context instance eg. params inside view (.edge) that we can use to help build our dynamic routes. But with inertia, we lose access to the context instance entirely.

We can overcome this limitation by passing the context instance as a shared data prop:

// start/inertia.ts
import Inertia from '@ioc:EidelLev/Inertia';

Inertia.share({
  params: ({ params }) => params,
});

Then we can access the params in our component like so:

import { usePage } from '@inertiajs/inertia-react';

const { params } = usePage().props;
stardust.route('users.show', { id: params.id });

Route Helper

If you have a page that doesn't need a corresponding controller method, like an FAQ or about page, you can route directly to a component.

// /start/routes.ts
import Route from '@ioc:Adonis/Core/Route';

Route.inertia('about', 'About');

// You can also pass root template data as the third parameter:
Route.inertia('about', 'About', { metadata: '...' });

Redirects

External redirects

Sometimes it's necessary to redirect to an external website, or even another non-Inertia endpoint in your app, within an Inertia request. This is possible using a server-side initiated window.location visit.

Route.get('redirect', async ({ inertia }) => {
  inertia.location('https://inertiajs.com/redirects');
});

Advanced

Server-side rendering

When Inertia detects that it's running in a Node.js environment, it will automatically render the provided page object to HTML and return it.

Setting up server side rendering

After configuring the the package using ace configure and enabling SSR, you will need to edit webpack.ssr.config.js. Set it up as you have your regular encore config to support your client-side framework of choice.

Adding an additional entrypoint

Create a new entrypoint resources/js/ssr.js (or ssr.ts/ssr.tsx if you prefer to use Typescript).

Your entrypoint code will depend on your client-side framework of choice:

React
import React from 'react';
import ReactDOMServer from 'react-dom/server';
import { createInertiaApp } from '@inertiajs/react';

export default function render(page) {
  return createInertiaApp({
    page,
    render: ReactDOMServer.renderToString,
    resolve: (name) => require(`./Pages/${name}`),
    setup: ({ App, props }) => <App {...props} />,
  });
}
Vue3
import { createSSRApp, h } from 'vue';
import { renderToString } from '@vue/server-renderer';
import { createInertiaApp } from '@inertiajs/vue3';

export default function render(page) {
  return createInertiaApp({
    page,
    render: renderToString,
    resolve: (name) => require(`./Pages/${name}`),
    setup({ app, props, plugin }) {
      return createSSRApp({
        render: () => h(app, props),
      }).use(plugin);
    },
  });
}
Vue2
import Vue from 'vue';
import { createRenderer } from 'vue-server-renderer';
import { createInertiaApp } from '@inertiajs/vue2';

export default function render(page) {
  return createInertiaApp({
    page,
    render: createRenderer().renderToString,
    resolve: (name) => require(`./Pages/${name}`),
    setup({ app, props, plugin }) {
      Vue.use(plugin);
      return new Vue({
        render: (h) => h(app, props),
      });
    },
  });
}
Svelte
import { createInertiaApp } from '@inertiajs/svelte';
import createServer from '@inertiajs/svelte/server';

createServer((page) =>
  createInertiaApp({
    page,
    resolve: (name) => require(`./Pages/${name}.svelte`),
  }),
);

Starting the SSR dev server

In a separate terminal run encore for SSR in watch mode:

node ace ssr:watch

Building SSR for production

node ace ssr:build

โ—In most cases you do not want the compiled javascript for ssr committed to source control. To avoid it, please add the inertia directory to .gitignore.

Customizing SSR output directory

By default, SSR assets will be emitted to inertia/ssr directory. If you prefer to use a different directory, you can change it by setting the buildDirectory parameter:

// /config/inertia.ts
{
  ssr: {
    enabled:true,
    buildDirectory: 'custom_path/ssr'
  }
}

You will also need to configure your SSR webpack config to output files to the same path.

Opting Out of SSR

Building isomorphic apps often comes with additional complexity. In some cases you may prefer to render only certain public routes on the server while letting the rest be rendered on the client. Luckily you can easily opt out of SSR by configuring a list of components that will rendered on the server, excluding all other components.

{
  ssr: {
    enabled:true,
    allowList: ['HomePage', 'Login']
  }
}

Authentication

AdonisJS provides us with powerful authentication and authorization APIs through @adonisjs/auth. After installing and setting up @adonisjs/auth you will need to set up exception handling to make it work with Inertia.

First, let's use @adonisjs/auth in our controller to authenticate the user:

// app/Controllers/Http/AuthController.ts
public async login({ auth, request, response }: HttpContextContract) {
  const loginSchema = schema.create({
    email: schema.string({ trim: true }, [rules.email()]),
    password: schema.string(),
  });

  const { email, password } = await request.validate({
    schema: loginSchema,
    messages: {
      required: 'This field is required',
      email: 'Please enter a valid email',
    },
  });

  await auth.use('web').attempt(email, password);

  response.redirect('/');
}

By default, AdonisJS will send an HTTP 400 response, which inertia does not know how to handle. Therefore, we will intercept this exception and redirect back to our login page (we can also optionally preserve the error message with flash messages).

// app/Exceptions/Handler.ts

import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext';
import HttpExceptionHandler from '@ioc:Adonis/Core/HttpExceptionHandler';
import Logger from '@ioc:Adonis/Core/Logger';

export default class ExceptionHandler extends HttpExceptionHandler {
  protected statusPages = {
    '403': 'errors/unauthorized',
    '404': 'errors/not-found',
    '500..599': 'errors/server-error',
  };

  constructor() {
    super(Logger);
  }

  public async handle(error: any, ctx: HttpContextContract) {
    const { session, response } = ctx;

    /**
     * Handle failed authentication attempt
     */
    if (['E_INVALID_AUTH_PASSWORD', 'E_INVALID_AUTH_UID'].includes(error.code)) {
      session.flash('errors', { login: error.message });
      return response.redirect('/login');
    }

    /**
     * Forward rest of the exceptions to the parent class
     */
    return super.handle(error, ctx);
  }
}

Asset Versioning

To enable automatic asset refreshing, you simply need to tell Inertia what the current version of your assets is. This can be any string (letters, numbers, or a file hash), as long as it changes when your assets have been updated.

To configure the current asset version, edit start/inertia.ts:

import Inertia from '@ioc:EidelLev/Inertia';

Inertia.version('v1');

// You can also pass a function that will be lazily evaluated:
Inertia.version(() => 'v2');

If you are using Adonis's built-in assets manager webpack encore you can also pass the path to the manifest file to Inertia and the current version will be set automatically:

Inertia.version(() => Inertia.manifestFile('public/assets/manifest.json'));

Setting Up View

You can set up the inertia root div in your view using the @inertia tag:

<body>
  @inertia
</body>

Contributing

This project happily accepts contributions.

Getting Started

After cloning the project run

npm ci
npx husky install # This sets up the project's git hooks

Before Making a Commit

This project adheres to the semantic versioning convention, therefore all commits must be conventional.

After staging your changes using git add, you can use the commitlint CLI to write your commit message:

npx commit

Before Opening a Pull Request

  • Make sure you add tests that cover your changes
  • Make sure all tests pass:
npm test
  • Make sure eslint passes:
npm run lint
  • Make sure your commit message is valid:
npx commitlint --edit

Thank you to all the people who already contributed to this project!

Issues

If you have a question or found a bug, feel free to open an issue.

inertiajs-adonisjs's People

Contributors

arthur-er avatar dkonsoftware avatar eidellev avatar janl avatar msurdi avatar treboryx avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

inertiajs-adonisjs's Issues

Adonis watch re-starting http server

I've tried to find information about the problem I have but have not been able to find an answer.

Not really the fault of this library... But maybe someone here has solved it (better than me).

I have an Adonis site with Inertia and it works as expected.
But when I save a file in my resources/js folder, the Adonis web server also restarts. Since it's a TypeScript file that has changed.
And since also the browser reloads, it returns a blank page.

I notice that the file watcher triggers whenever a file is changed:
https://github.com/adonisjs/assembler/blob/develop/src/DevServer/index.ts#L299

I'm not sure exactly how this works but managed to patch the DevServer to check if the files exist in "metaFiles" .adonisrc.json and don't restart the server if it has that setting. But this seems like a "hacky" solution...

Does this work using Typescript in Svelte?

I got this whole thing to work with Svelte, however, when I try to use lang="ts" in the .svelte files, I'm just getting numerous errors like an imported custom component not found etc.

I'm not sure if this is more of a Typescript config issue or something else?

Inertia XHR response returns wrong URL when i use inertia.visit with array params

Hello! I have an issue with $inertia.visit, when i try to visit page with url array of values Inertia makes xhr get request properly. But after inertia replaces browser url not correctly, instead of doing like this: ?querystring[]=123&querystring[]=321 inertia replaces url like ?querystring=123,321. So after page refresh my backend receive string instead of array

Steps to reproduce:
Make a visit with array of data, in my case IDs like [1,2,3]

this.$inertia.visit('/admin/reservation/list/', {
data: {
venicleSearch: value, //array of ids
},
preserveState: true,
only: ['reservations'],
onSuccess: () => {
this.venicleSearchLoading = false
},
})

In screenshot below you can see inertia behavior

image

Form data ends up in the url

Hello, i am trying to do a form submission but when i a submit the form and get the response, the url changes to include the posted data into the url. Am i submitting/handling the form wrong?

The form submission

submit(form) {
      form
        .transform((data) => ({
          ...data,
          location: data.location.id ?? null,
          sport: data.sport.id ?? null,
        }))
        .post('/games/new', {
          onSuccess: () => {
            this.$toast.success('Game created.', {
              // optional options Object
            })
          },
        })
    }

The response from the handler for POST /games/new

return inertia.render('games/New', {
        sports,
        game: game.id,
      })

Thank you for your help

How to resolve ESlint to work with vue extension?

Parsing error: ESLint was configured to run on <tsconfigRootDir>/resources\js\Pages\Home.vue using parserOptions.project: /tsconfig.json
The extension for the file (.vue) is non-standard. You should add parserOptions.extraFileExtensions to your config.

how can get route info?

If you're using Laravel, the Ziggy library does this for you automatically via a global route() function. If you're using Ziggy with Vue, it's helpful to make this function available as a custom $route property so you can use it directly in your templates.

How can I do exact same thing in Adonis project?

How to add type definition for shared data

Hello @eidellev. Thank you for this wonderful package. I am using it with Vue 3 and Typescript. I can't find how to add type definitions for shared data.

Although it is working, Typescript is complaining that those properties are unknown and I don't get suggestions.

How can I add type definitions for shared data?

The ace config should also add the script tag.

When running the ace command to configure inertiajs-adonisjs it creates without <script src="{{ asset('assets/app.js') }}" defer></script> so it doesn't work at all.

Both the script for creating the app.edge and the docs should mention that this file is necessary.

What does the manifest.json file in the public/assets folder do?

Hi, I set up an app using Vue 3 with Vite and Inertia using your config. However, I kept getting a message "Manifest file could not be read". I'm guessing it hadn't been automatically created for some reason. Everything worked fine though.

I created a manifest.json file at public/assets with simply an empty JSON object and the message went away. So what does that file do and what is the point of it?

Error upgrading to version 2.0.1

I just tried upgrading from version 1.0.1 to the latest 2.0.1 and ran into ERESOLVE unable to resolve dependency tree issue. I doubt if this has to do with the fact that this package seems to depend on both @adonis/config 3.x and 2.x: https://github.com/eidellev/inertiajs-adonisjs/blob/main/package.json#L51

npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR! 
npm ERR! While resolving: [email protected]
npm ERR! Found: @adonisjs/[email protected]
npm ERR! node_modules/@adonisjs/config
npm ERR!   dev @adonisjs/config@"^3.0.0" from the root project
npm ERR! 
npm ERR! Could not resolve dependency:
npm ERR! peer @adonisjs/config@"^2.0.3" from @eidellev/[email protected]
npm ERR! node_modules/@eidellev/inertia-adonisjs
npm ERR!   @eidellev/inertia-adonisjs@"^2.0.1" from the root project
npm ERR! 
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.

getting null on the controller endpoint wile uploading a file

I am sorry for re open the same issue. actully I am doing same what you suggested previously. just one different thing is i am not using typeScript in react.

The Problem is still i am getting null in the controller endpoint. i am selecting valid image file. and when submit it console shows that the value of the file is null.

Repo: https://github.com/dmostafiz/adonartia

React Component

Screenshot 2022-02-19 230618

Controller

Screenshot 2022-02-19 230719

Console log

Screenshot 2022-02-19 230536

and getting this error in the browser console

Screenshot 2022-02-19 231829

Unexpected token '<'

Hi, thanks for the wonderful solution.
React with typescript is working perfectly fine without SSR.

But when I try to make SSR enabled. I'm getting

[1656072804998] ERROR (rita/2945 on machist): Unexpected token '<'
    err: {
      "type": "SyntaxError",
      "message": "Unexpected token '<'",
      "stack":
          /home/borag/Tmp/rita/resources/js/pages/auth/register.tsx:22
              return (<Layout_1.default links={[]}>
                      ^

          SyntaxError: Unexpected token '<'
              at Object.compileFunction (node:vm:352:18)
              at wrapSafe (node:internal/modules/cjs/loader:1033:15)
              at Module._compile (node:internal/modules/cjs/loader:1069:27)
              at Module._compile (/home/borag/Tmp/rita/node_modules/pirates/lib/index.js:136:24)
              at Module._extensions..js (node:internal/modules/cjs/loader:1159:10)
              at Object.newLoader [as .tsx] (/home/borag/Tmp/rita/node_modules/pirates/lib/index.js:141:7)
              at Module.load (node:internal/modules/cjs/loader:981:32)
              at Function.Module._load (node:internal/modules/cjs/loader:822:12)
              at Module.require (node:internal/modules/cjs/loader:1005:19)
              at require (node:internal/modules/cjs/helpers:102:18)
      "status": 500
    }

Failure to lookup `@ioc:EidelLev/Inertia`

PS C:\Users\user\Development\Anomia\Anomia-Backend> node ace serve
[ info ]  building project...
[ info ]  starting http server...

IocLookupException: E_IOC_LOOKUP_FAILED: Cannot resolve "EidelLev/Inertia" namespace from the IoC Container

at C:\Users\user\Development\Anomia\Anomia-Backend\start\inertia.ts(anonymous):11
6   | Any code written inside this file will be executed during the application
7   | boot.
8   |
9   */
10
11  import Inertia from '@ioc:EidelLev/Inertia';
12  ^^^^^^^^^^^^^^^^^^^^^^^^^^

Here's where its highlited as the error origin.
The rest is just some more info.

13  Inertia.share({
14    errors: (ctx) => {
15      return ctx.session.flashMessages.get('errors');
16    },

1 Function.lookupFailed
  C:\Users\user\Development\Anomia\Anomia-Backend\node_modules\@adonisjs\fold\build\src\Exceptions\IocLookupException.js:18

2 Ioc.lookupOrFail
  C:\Users\user\Development\Anomia\Anomia-Backend\node_modules\@adonisjs\fold\build\src\Ioc\index.js:254

3 Ioc.use
  C:\Users\user\Development\Anomia\Anomia-Backend\node_modules\@adonisjs\fold\build\src\Ioc\index.js:308

4 Module._compile
  C:\Users\user\Development\Anomia\Anomia-Backend\node_modules\pirates\lib\index.js:99

5 Object.newLoader [as .ts]
  C:\Users\user\Development\Anomia\Anomia-Backend\node_modules\pirates\lib\index.js:104

[ warn ]  Underlying HTTP server died with "0 code"
PS C:\Users\user\Development\Anomia\Anomia-Backend> 

Context:

I was making a REST API application, but figured that in my case it could be better to use InertiaJS, so I installed adonisjs session module aswell as InertiaJS, following the tutorials, and adding the middleware.

My use case is really simple;

import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'

export default class AuthController {
  public async sendShit({ inertia }: HttpContextContract) {
    inertia.render('auth/auth', {
      ok: 'Jhon!',
    })
  }
}

For some reason VSCode can find the module, but Adonis is not capable.

Controller
image
start/inertia.ts
image
image

import Inertia from '@ioc:EidelLev/Inertia';

Inertia.share({
  errors: (ctx) => {
    return ctx.session.flashMessages.get('errors');
  },
}).version(() => Inertia.manifestFile('public/assets/manifest.json'));

I asked this on the Discord and they told me to check my providers in adonisrc.json file, it's there.

  "providers": [
    "./providers/AppProvider",
    "@adonisjs/core",
    "@adonisjs/lucid",
    "@adonisjs/auth",
    "adonisjs-hcaptcha",
    "@eidellev/inertia-adonisjs",
    "@adonisjs/session"
  ],

Is there way to define multiple app.edge views?

Hello, thanks for this plugin.
I want to set multiple edge entrypoints, is there way to do this?
For example app.edge for public and admin.edge for admin with own webpack encore assets ?

Plain json issue

I launched my project to production recently and i faced issue returning plain/json text instead of rendered page on mobile android/chrome. I also tried to kind of reproduce it on dev server (new project and my existing project) and it confirms on localhost

Steps to reproduce it on mobile:
1.Visit app,
2. click on inertia link
3. after page was rendered try to close all apps in android (throught the "recent apps" button from android system navigation)
4. Open Chrome again
image

It's not necessary to close, you can actually minimize the browser, try use other apps then open it again

Steps to reproduce it on dev server (in my case PC/Windows)
1.Visit app on Chrome
2. Click inertia-link
3. Kill Google Chrome browser process from task manager
4. Open Chrome again, Chrome will suggest you to restore unexpedetly closed tabs. Restore it and you will see plain json response
5. application renders properly only after you reload the page in browser

image

@inertiaHead don't work

Hi ! I use import { Head } from '@inertiajs/inertia-vue3' i think, and the content i put in , is rendered inside the div of the app as a tag, but not added in the where @inertiaHead is placed.

I use SSR, do you have an idea ?

Thanks !

Redirects with inertia.location don't work because X-Inertia=true header is sent

I had some problems using inertia.location(...) in my application.

According to the Inertia docs, the server should send a 409 Conflict response, with the destination in the X-Inertia-Location header.

Looking at the request, it does indeed do this. However, there are two Inertia headers:

x-inertia true
x-inertia-location http://<redacted>/auth/login

I asked for help in the Discord channel for Inertia and it was pointed out to me that:

  • According to the protocol, there should only be an X-Inertia-Location header - X-Inertia should not be present for a redirect to happen.

  • The presence of X-Inertia causes setPage() to be called in Inertia (see here).

So, instead of using inertia.location(), I set the headers manually:

response.header('X-Inertia-Location', <some url>)
response.removeHeader('X-Inertia') // ๐Ÿ‘ˆ removing X-Inertia
return response.conflict()

... and it works perfectly.


Also, on a side note, using inertia.location() causes a TypeScript error:

Property 'location' does not exist on type 'InertiaContract'.

watch - hot reload

Hi guys ๐Ÿ‘‹

This might just be a question and not really an issue.

I am new to InertiaJS and Vue.

I've configured adonis webpack and ssr webpack as described on docs.
Both webpacks, ssr and standard adonis one watch for changes and compile as necessary with following commands:
node ace ssr:watch and node ace serve --watch respectively.

Now, changing .edge files the hot reload works fine and is displayed correctly, however the ssr one (when modifying Vue files) is not although webpack compiles fine.

For changes to take effect I need to restart adonisjs app and re-start it with the above command, and I feel like I am doing something wrong since watch function should do that out of the box?

The only thing that is not as default is ssr build which is set to /build/inertia/ssr instead.

Is this how it supposed to be? Restart the server on vue changes?

Thanks in advance!

Here are my webpack configs:

webpack.ssr.config:

const { join } = require('path')
const Encore = require('@symfony/webpack-encore')

/*
|--------------------------------------------------------------------------
| Encore runtime environment
|--------------------------------------------------------------------------
*/
if (!Encore.isRuntimeEnvironmentConfigured()) {
  Encore.configureRuntimeEnvironment(process.env.NODE_ENV || 'dev')
}

/*
|--------------------------------------------------------------------------
| Output path
|--------------------------------------------------------------------------
|
| The output path for writing the compiled files. It should always
| be inside the public directory, so that AdonisJS can serve it.
|
*/
Encore.setOutputPath('./build/inertia/ssr')

/*
|--------------------------------------------------------------------------
| Public URI
|--------------------------------------------------------------------------
|
| The public URI to access the static files. It should always be
| relative from the "public" directory.
|
*/
Encore.setPublicPath('/ssr')

/*
|--------------------------------------------------------------------------
| Entrypoints
|--------------------------------------------------------------------------
|
| Entrypoints are script files that boots your frontend application. Ideally
| a single entrypoint is used by majority of applications. However, feel
| free to add more (if required).
|
| Also, make sure to read the docs on "Assets bundler" to learn more about
| entrypoints.
|
*/
Encore.addEntry('ssr', './resources/js/ssr.js')

/*
|--------------------------------------------------------------------------
| Isolated entrypoints
|--------------------------------------------------------------------------
|
| Treat each entry point and its dependencies as its own isolated module.
|
*/
Encore.disableSingleRuntimeChunk()

/*
|--------------------------------------------------------------------------
| Cleanup output folder
|--------------------------------------------------------------------------
|
| It is always nice to cleanup the build output before creating a build. It
| will ensure that all unused files from the previous build are removed.
|
*/
Encore.cleanupOutputBeforeBuild()

/*
|--------------------------------------------------------------------------
| Assets versioning
|--------------------------------------------------------------------------
|
| Enable assets versioning to leverage lifetime browser and CDN cache
|
*/
Encore.enableVersioning(Encore.isProduction())

/*
|--------------------------------------------------------------------------
| Configure dev server
|--------------------------------------------------------------------------
|
| Here we configure the dev server to enable live reloading for edge templates.
| Remember edge templates are not processed by Webpack and hence we need
| to watch them explicitly and livereload the browser.
|
*/
Encore.configureDevServerOptions((options) => {
  /**
   * Normalize "options.static" property to an array
   */
  if (!options.static) {
    options.static = []
  } else if (!Array.isArray(options.static)) {
    options.static = [options.static]
  }

  /**
   * Enable live reload and add views directory
   */

  options.liveReload = true
  options.static.push({
    directory: join(__dirname, './resources/js/Pages'),
    watch: true,
  })
})

/*
|--------------------------------------------------------------------------
| CSS precompilers support
|--------------------------------------------------------------------------
|
| Uncomment one of the following lines of code to enable support for your
| favorite CSS precompiler
|
*/
// Encore.enableSassLoader()
// Encore.enableLessLoader()
// Encore.enableStylusLoader()

/*
|--------------------------------------------------------------------------
| CSS loaders
|--------------------------------------------------------------------------
|
| Uncomment one of the following line of code to enable support for
| PostCSS or CSS.
|
*/
// Encore.enablePostCssLoader()
// Encore.configureCssLoader(() => {})

/*
|--------------------------------------------------------------------------
| Enable Vue loader
|--------------------------------------------------------------------------
|
| Uncomment the following lines of code to enable support for vue. Also make
| sure to install the required dependencies.
|
*/
Encore.enableVueLoader(() => {}, {
  version: 3,
  runtimeCompilerBuild: false,
  useJsx: false,
})

/*
|--------------------------------------------------------------------------
| Configure logging
|--------------------------------------------------------------------------
|
| To keep the terminal clean from unnecessary info statements , we only
| log warnings and errors. If you want all the logs, you can change
| the level to "info".
|
*/
const config = Encore.getWebpackConfig()
config.infrastructureLogging = {
  level: 'warn',
}
config.stats = 'errors-warnings'

/*
|--------------------------------------------------------------------------
| SSR Config
|--------------------------------------------------------------------------
|
*/
config.externals = [require('webpack-node-externals')()]
config.externalsPresets = { node: true }
config.output = {
  libraryTarget: 'commonjs2',
  filename: 'ssr.js',
  path: join(__dirname, './build/inertia/ssr'),
}
config.experiments = { outputModule: true }

/*
|--------------------------------------------------------------------------
| Export config
|--------------------------------------------------------------------------
|
| Export config for webpack to do its job
|
*/

module.exports = config

webpack.config:

const { join } = require('path')
const Encore = require('@symfony/webpack-encore')
const TerserPlugin = require('terser-webpack-plugin')

/*
|--------------------------------------------------------------------------
| Encore runtime environment
|--------------------------------------------------------------------------
*/
if (!Encore.isRuntimeEnvironmentConfigured()) {
	Encore.configureRuntimeEnvironment(process.env.NODE_ENV || 'dev')
}

/*
|--------------------------------------------------------------------------
| Output path
|--------------------------------------------------------------------------
|
| The output path for writing the compiled files. It should always
| be inside the public directory, so that AdonisJS can serve it.
|
*/
Encore.setOutputPath('./public/assets')

/*
|--------------------------------------------------------------------------
| Public URI
|--------------------------------------------------------------------------
|
| The public URI to access the static files. It should always be
| relative from the "public" directory.
|
*/
Encore.setPublicPath('/assets')

/*
|--------------------------------------------------------------------------
| Entrypoints
|--------------------------------------------------------------------------
|
| Entrypoints are script files that boots your frontend application. Ideally
| a single entrypoint is used by majority of applications. However, feel
| free to add more (if required).
|
| Also, make sure to read the docs on "Assets bundler" to learn more about
| entrypoints.
|
*/
Encore.addEntry('app', './resources/js/app.js')
Encore.addEntry('style', './resources/src/style.css')

/*
|--------------------------------------------------------------------------
| Copy assets
|--------------------------------------------------------------------------
|
| Since the edge templates are not part of the Webpack compile lifecycle, any
| images referenced by it will not be processed by Webpack automatically. Hence
| we must copy them manually.
|
*/
// Encore.copyFiles({
//   from: './resources/images',
//   to: 'images/[path][name].[hash:8].[ext]',
// })

/*
|--------------------------------------------------------------------------
| Split shared code
|--------------------------------------------------------------------------
|
| Instead of bundling duplicate code in all the bundles, generate a separate
| bundle for the shared code.
|
| https://symfony.com/doc/current/frontend/encore/split-chunks.html
| https://webpack.js.org/plugins/split-chunks-plugin/
|
*/
Encore.splitEntryChunks()

/*
|--------------------------------------------------------------------------
| Isolated entrypoints
|--------------------------------------------------------------------------
|
| Treat each entry point and its dependencies as its own isolated module.
|
*/
Encore.disableSingleRuntimeChunk()

/*
|--------------------------------------------------------------------------
| Cleanup output folder
|--------------------------------------------------------------------------
|
| It is always nice to cleanup the build output before creating a build. It
| will ensure that all unused files from the previous build are removed.
|
*/
Encore.cleanupOutputBeforeBuild()

/*
|--------------------------------------------------------------------------
| Source maps
|--------------------------------------------------------------------------
|
| Enable source maps in production
|
*/
Encore.enableSourceMaps(!Encore.isProduction())

/*
|--------------------------------------------------------------------------
| Assets versioning
|--------------------------------------------------------------------------
|
| Enable assets versioning to leverage lifetime browser and CDN cache
|
*/
Encore.enableVersioning(Encore.isProduction())

/*
|--------------------------------------------------------------------------
| Configure dev server
|--------------------------------------------------------------------------
|
| Here we configure the dev server to enable live reloading for edge templates.
| Remember edge templates are not processed by Webpack and hence we need
| to watch them explicitly and livereload the browser.
|
*/
Encore.configureDevServerOptions((options) => {
	/**
	 * Normalize "options.static" property to an array
	 */
	if (!options.static) {
		options.static = []
	} else if (!Array.isArray(options.static)) {
		options.static = [options.static]
	}

	/**
	 * Enable live reload and add views directory
	 */
	options.liveReload = true
	options.static.push({
		directory: join(__dirname, './resources/views'),
		watch: true,
	})

})

/*
|--------------------------------------------------------------------------
| CSS precompilers support
|--------------------------------------------------------------------------
|
| Uncomment one of the following lines of code to enable support for your
| favorite CSS precompiler
|
*/
// Encore.enableSassLoader()
// Encore.enableLessLoader()
// Encore.enableStylusLoader()

/*
|--------------------------------------------------------------------------
| CSS loaders
|--------------------------------------------------------------------------
|
| Uncomment one of the following line of code to enable support for
| PostCSS or CSS.
|
*/
Encore.enablePostCssLoader((options) => {
	options.postcssOptions = {
		// the directory where the postcss.config.js file is stored
		config: './postcss.config.js',
	}
})
// .configureCssLoader(() => {})

/*
|--------------------------------------------------------------------------
| Terser Plugin
|--------------------------------------------------------------------------
|
| For minifying and mangling JS code
|
*/
if (Encore.isProduction()) {
	Encore.addPlugin(
		new TerserPlugin({
			terserOptions: {
				format: {
					comments: false,
				},
			},
			extractComments: false,
		})
	)
}

/*
|--------------------------------------------------------------------------
| Webpack JQuery
|--------------------------------------------------------------------------
|
| Automatically provides jquery globally
|
*/

Encore.autoProvidejQuery()

/*
|--------------------------------------------------------------------------
| Enable Vue loader
|--------------------------------------------------------------------------
|
| Uncomment the following lines of code to enable support for vue. Also make
| sure to install the required dependencies.
|
*/
// Encore.enableVueLoader(() => {}, {
//   version: 3,
//   runtimeCompilerBuild: false,
//   useJsx: false
// })

/*
|--------------------------------------------------------------------------
| Configure logging
|--------------------------------------------------------------------------
|
| To keep the terminal clean from unnecessary info statements , we only
| log warnings and errors. If you want all the logs, you can change
| the level to "info".
|
*/
const config = Encore.getWebpackConfig()
config.infrastructureLogging = {
	level: 'warn',
}
config.stats = 'errors-warnings'

/*
|--------------------------------------------------------------------------
| Export config
|--------------------------------------------------------------------------
|
| Export config for webpack to do its job
|
*/
module.exports = config

Intercept All Inertia requests must receive a valid Inertia response

Hello,

Is there a way I can intercept All Inertia requests must receive a valid Inertia response errors and perform some tasks? Actually I am trying to log errors to some crash reporting platform. I am able to catch and log errors with status 400 and 500 but since All Inertia requests must receive a valid Inertia response, has a status code of 200-300 I am not able to capture such errors.

Any help will be appreciated.

Thank you.

Building issue

Hi !
At this time I was always using the dev mode and it works great.
But now, I want to build, and the Vue code compile great, but not in a build folder ?
And when it's the time to compile Adonisjs code, I have error in all files, like "[insert a var here] is declared but its value is never read." and many others.
Anyone have theses errors ?

File upload problem witn react, inertia and adonis

Hello, i am just started with inertia react and adonis js. it seems everything okay, but when i am trying to upload file following inertia js official documentation i found and error like

"index.js:1 Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'toString')"

and from the controller i am not getting any file reference to work with. if i am wrong anywhere to implement that, please guide me.

The automated release is failing ๐Ÿšจ

๐Ÿšจ The automated release from the main branch failed. ๐Ÿšจ

I recommend you give this issue a high priority, so other packages depending on you could benefit from your bug fixes and new features.

You can find below the list of errors reported by semantic-release. Each one of them has to be resolved in order to automatically publish your package. Iโ€™m sure you can resolve this ๐Ÿ’ช.

Errors are usually caused by a misconfiguration or an authentication problem. With each error reported below you will find explanation and guidance to help you to resolve it.

Once all the errors are resolved, semantic-release will release your package the next time you push a commit to the main branch. You can also manually restart the failed CI job that runs semantic-release.

If you are not sure how to resolve this, here is some links that can help you:

If those donโ€™t help, or if this issue is reporting something you think isnโ€™t right, you can always ask the humans behind semantic-release.


No npm token specified.

An npm token must be created and set in the NPM_TOKEN environment variable on your CI environment.

Please make sure to create an npm token and to set it in the NPM_TOKEN environment variable on your CI environment. The token must allow to publish to the registry https://registry.npmjs.org/.


Good luck with your project โœจ

Your semantic-release bot ๐Ÿ“ฆ๐Ÿš€

Flash messages issue

Hi! I'm tryin to configure snackbar notifications using Adonisjs session flash, after creating new row through the POST method

I set session flash message then redirect to another path in adonis controller but my vue app can't see any changes in $page.props.[shared data name]

My adonisjs controller:
"create" method:
image

"list" method:
image

In chrome dev tools network tab i can see server responds properly with shared data (with flash messages)
image

Seems like inertia adapter or inertia self not updating $page variable

start/inertia.ts
image

i set watcher in Vue 2 like this (in layout component)
image
additionally i put console log to watcher and watcher's value staying changeless.

Also i tried to set preserveState but no result

But ihave several cases, where notifications works properly,

  1. when i use manual request $inertia.delete() with method spoofing and redirecting to same page it works
    image

When i'm staying on same page for example "/admin/reservation/list" and trying to create new "reservation" using modal dialog

Critical dependency: Accessing import.meta directly is unsupported (only property access is supported)

On a clean install using step by step this error occurs when running dev mode.

When do you use vite

import { createApp, h } from 'vue'
import { createInertiaApp } from '@inertiajs/vue3'

createInertiaApp({
resolve: name => {
const pages = import.meta.glob('./Pages/**/*.vue', { eager: true })
return pages[./Pages/${name}.vue]
},
setup({ el, App, props, plugin }) {
createApp({ render: () => h(App, props) })
.use(plugin)
.mount(el)
},
})

[ encore ] WARN Compiled with 1 warnings00:11:56
[ encore ] warn in ./resources/js/app.js00:11:56
[ encore ] Critical dependency: Accessing import.meta directly is unsupported (only property access is supported)
[ encore ] WARNING in ./resources/js/app.js 6:16-27
Critical dependency: Accessing import.meta directly is unsupported (only property access is supported)

Using SSR causes : Cannot use 'import.meta' outside a module

webpack.config.js: https://pastebin.com/TqBTuZNf
webpack.ssr.config.js: https://pastebin.com/7eSR3tD5

As you can see, I use a Inertia-React-Tailwind stack.

When navigating to a route of my app, Adonis throws this error:

[18:50:01.079] ERROR (hydra/18528): Cannot use 'import.meta' outside a module
    err: {
      "type": "SyntaxError",
      "message": "Cannot use 'import.meta' outside a module",
      "stack":
          D:\Programmation\Perso\hydra\build\inertia\ssr\ssr.js:1514
          /******/      if (typeof import.meta.url === "string") scriptUrl = import.meta.url
                                          ^^^^

          SyntaxError: Cannot use 'import.meta' outside a module
              at internalCompileFunction (node:internal/vm:74:18)
              at wrapSafe (node:internal/modules/cjs/loader:1141:20)
              at Module._compile (node:internal/modules/cjs/loader:1182:27)
              at Object.Module._extensions..js (node:internal/modules/cjs/loader:1272:10)
              at Module.load (node:internal/modules/cjs/loader:1081:32)
              at Function.Module._load (node:internal/modules/cjs/loader:922:12)
              at Module.require (node:internal/modules/cjs/loader:1105:19)
              at require (node:internal/modules/cjs/helpers:103:18)
              at Inertia.renderSsrPage (REDACTED\node_modules\@eidellev\inertia-adonisjs\build\src\Inertia.js:97:24)
              at Inertia.render (REDACTED\node_modules\@eidellev\inertia-adonisjs\build\src\Inertia.js:77:47)
      "status": 500
    }

It seems to generate ESM code import.meta that obviously fail.

Did I do something wrong?

Deploying to production

First off, great job on this! I had my app deployed to production as a non-ssr application and it was working fine. After getting SSR configured I ran into issues with it saying the module inertia/ssr/ssr.js couldn't be found. Come to find out, it was expecting the inertia/ssr directory to be locted inside of the build directory, but that doesn't seem to happen by default.

I ended up fixing the problem by changing the build directory inside of webpack.ssr.config.js to build/inertia/ssr, but I wanted to know if there's a better way because that just feels kinda hacky.

SSR Support

SSR Support for Inertia is officially out, and should be here as well

Currrently Inertia docs suggests running a separate server for rendering the pages as the official adapters don't run in NodeJS, but as Adonis is a NodeJS framework we can add support for Inertia SSR on the same server.

I'm currently using SSR without support from the adapter (using a view global that renders and returns the inertia page) and its working as a breeze.

My suggestion to implement this is just including a SSR Render config function on the already existing inertia config that receives the render function to support different front-end frameworks and include the SSR request in the existing @inertia edge tag with a extra @inertiaHead tag to match Inertia Laravel implementation

I'm willing to work in this if approved

Client-side interactivity doesn't seem to be working with SSR

I'm new to the SSR aspect of Inertia. I followed the instructions and everything seems to work just fine, until I try to do any sort of client-side interactivity:

<button onClick={() => alert('hello!')}>say hello</button>

When I click the button, nothing happens.

This is my ssr.tsx file:

import { createInertiaApp } from '@inertiajs/inertia-react'
import ReactDOMServer from 'react-dom/server'

export default function render(page) {
  return createInertiaApp({
    page,
    render: ReactDOMServer.renderToString,
    resolve: (name) => require(`./pages/${name}`),
    setup: ({ App, props }) => <App {...props} />,
  })
}

As far as I can remember, these are the only things that I changed in webpack.ssr.config.ts:

Encore.addEntry('ssr', './resources/js/ssr.tsx').enableTypeScriptLoader()

and for Tailwind:

Encore.enablePostCssLoader()

The source of the page looks like this (notice app.js is present, as you'd expect):

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="icon" type="image/png" href="http://localhost:3333/favicon.ico">
    <link rel="stylesheet" href="http://localhost:8080/assets/app.css" />
    <script src="http://localhost:8080/assets/app.js" defer></script>

    <title>test-app</title>
</head>

<body>
    <div id="app" data-page="{&quot;component&quot;:&quot;Auth/Login&quot;,&quot;version&quot;:&quot;e77ee25438e9f73dc55c00b5e3ee4e15&quot;,&quot;props&quot;:{},&quot;url&quot;:&quot;/auth/login&quot;}">
        <button>say hello</button>
    </div>
</body>

</html>

To me, it seems like the HTML isn't being hydrated.

I was wondering if I could get some help to figure it out.

Metadata param in Route Helper

I can't find a solution to add metadata (for root Edge file) in Route Helper

<meta name="twitter:title" content="{{ page.title }}">

Maybe this signature could be added

// /start/routes.ts
import Route from '@ioc:Adonis/Core/Route';

Route.inertia('about', 'About', { metadata: '...' });

Any advice or solution?

Unexpected token '<'

Anyone getting this error when adding the following in inertia config?

  ssr: {
    enabled: true,
    mode: 'react', // can also be 'vue2', 'vue3', 'svelte'
    pageRootDir: 'js/pages', // Where inertia should look for page components
  }

Without it, all good, but no SSR.

Flash message not found

Hello, I am trying to use the quick messages but they do not appear. Did I forget something?

Controller
Screenshot 2022-05-25 at 10 52 37

start/inertia.ts
Screenshot 2022-05-25 at 10 52 46

And i print {{ $page }}
Screenshot 2022-05-25 at 10 53 29

but in the doc of inertiajs
Screenshot 2022-05-25 at 10 59 03

I don't have the flash object

Adonis routes in the frontend view

Is there a way to generate and use the adonisjs routes in the view. Like ziggy for laravel where there is a global $routes. Is there any option or available package similar to this or any other way to make it work.
Thanks

ssr abnormal behavior

thank you for your amazing job

i finished a app with your awesome package

everything work perfectly

but ssr have abnormal behavior

<Head>
<component is="script" type="application/ld+json">
      {
      "@context": "https://schema.org/",
      "@type": "Article",
      ....
      },
       "datePublished": "{{ new Date(post.created_at).toISOString().substr(0, 10) }}",
      "dateCreated": "{{ new Date(post.created_at).toISOString().substr(0, 10) }}",
      "dateModified":"{{ new Date(post.updated_at).toISOString().substr(0, 10) }}"
      }
    </component>
</Head>

this is not working and throw an error because post.updated_at or post.created_at is undefined

but this way its working

<Head>
<component is="script" type="application/ld+json">
      {
      "@context": "https://schema.org/",
      "@type": "Article",
      ....
      },
     "datePublished": "{{ new Date(JSON.parse(JSON.stringify(post)).created_at).toISOString().substr(0, 10) }}",
      "dateCreated": "{{ new Date(JSON.parse(JSON.stringify(post)).created_at).toISOString().substr(0, 10) }}",
      "dateModified":"{{ new Date(JSON.parse(JSON.stringify(post)).updated_at).toISOString().substr(0, 10) }}"
      }
    </component>
</Head>

and when i am using curl or view:source ,head retunes everything without problem

<script inertia type="application/ld+json"> {
  "@context": "https://schema.org",
  "@type": "LocalBusiness",
  ...
  "sameAs": [
    "https://t.me/blala",
    "https://www.instagram.com/blala",
    "https://twitter.com/blala"
  ]
} </script>
 

but when page loads in browser its change to empty script tag

<script type="application/ld+json" inertia=""></script>

exmpale site

nodejs 18.13.0

inertiajs-adonisjs 7.4.0

Is there a complete example for ssr

I tried the following steps but it never works.

// create project
yarn create adonis-ts-app adonis-inertia-vue

// choice it api
cd adonis-inertia-vue
node ace serve --watch

// is works, show like this `{hello:world}`
// add inertiajs-adonisjs 
yarn add @eidellev/inertia-adonisjs

// add view and session
yarn add @adonisjs/view
yarn add @adonisjs/session

// configure inertiajs-adonisjs
node ace configure @eidellev/inertia-adonisjs

// set ssr `Y` and choice vue3

create resources/js/ssr.js and write this

import { createSSRApp, h } from 'vue';
import { renderToString } from '@vue/server-renderer';
import { createInertiaApp } from '@inertiajs/inertia-vue3';

export default function render(page) {
  return createInertiaApp({
    page,
    render: renderToString,
    resolve: (name) => require(`./Pages/${name}`),
    setup({ app, props, plugin }) {
      return createSSRApp({
        render: () => h(app, props),
      }).use(plugin);
    },
  });
}

change webpack.ssr.config.js to enabled vue3

run command

node ace ssr:watch

then

yarn add vue@^3.2.14 vue-loader@^17.0.0 @vue/compiler-sfc --dev

rerun

node ace ssr:watch
// console like this
// 2 files written to inertia/ssr
// webpack compiled successfully

but when run command node ace serve its show this

[ info ]  building project...
[ info ]  starting http server...
[1659787135295] INFO (adonis-vue-inertia-ssr/86597 on xxxdeMac-mini.local): started server on 0.0.0.0:3333
โ•ญโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ
โ”‚                                                        โ”‚
โ”‚    Server address: http://127.0.0.1:3333               โ”‚
โ”‚    Watching filesystem for changes: NO                 โ”‚
โ”‚    Encore server address: http://localhost:8080        โ”‚
โ”‚                                                        โ”‚
โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ
[ encore ] Running webpack-dev-server ...
[ encore ] <i> [webpack-dev-server] Project is running at:
[ encore ] <i> [webpack-dev-server] Loopback: http://localhost:8080/
[ encore ] <i> [webpack-dev-server] On Your Network (IPv4): http://192.168.31.158:8080/
<i> [webpack-dev-server] On Your Network (IPv6): http://[fe80::1]:8080/
<i> [webpack-dev-server] Content not from webpack is served from '/Users/xxx/ExampleCode/adonis-vue-inertia-ssr/public' directory
[ encore ] assets by status 115 KiB [cached] 1 asset
runtime modules 27.3 KiB 12 modules
orphan modules 18.8 KiB [orphan] 8 modules
cacheable modules 158 KiB
  modules by path ./node_modules/webpack-dev-server/client/ 53.5 KiB
    ./node_modules/webpack-dev-server/client/index.js?protocol=ws%3A&hostname=0.0.0.0&port=8080&pathname=%2Fws&logging=info&reconnect=10 + 8 modules 25.7 KiB [built] [code generated]
    + 3 modules
  modules by path ./node_modules/webpack/hot/*.js 4.3 KiB
    ./node_modules/webpack/hot/dev-server.js 1.59 KiB [built] [code generated]
    + 3 modules
  modules by path ./node_modules/html-entities/lib/*.js 81.3 KiB
    ./node_modules/html-entities/lib/index.js 7.74 KiB [built] [code generated]
    ./node_modules/html-entities/lib/named-references.js 72.7 KiB [built] [code generated]
    + 2 modules
  ./node_modules/ansi-html-community/index.js 4.16 KiB [built] [code generated]
  ./node_modules/events/events.js 14.5 KiB [built] [code generated]

WARNING in configuration
The 'mode' option has not been set, webpack will fallback to 'production' for this value.
Set 'mode' option to 'development' or 'production' to enable defaults for each environment.
You can also set it to 'none' to disable any default behavior. Learn more: https://webpack.js.org/configuration/mode/

ERROR in main
Module not found: Error: Can't resolve './src' in '/Users/xxx/ExampleCode/adonis-vue-inertia-ssr'
resolve './src' in '/Users/xxx/ExampleCode/adonis-vue-inertia-ssr'
  using description file: /Users/xxx/ExampleCode/adonis-vue-inertia-ssr/package.json (relative path: .)
    Field 'browser' doesn't contain a valid alias configuration
    using description file: /Users/xxx/ExampleCode/adonis-vue-inertia-ssr/package.json (relative path: ./src)
      no extension
        Field 'browser' doesn't contain a valid alias configuration
        /Users/xxx/ExampleCode/adonis-vue-inertia-ssr/src doesn't exist
      .js
        Field 'browser' doesn't contain a valid alias configuration
        /Users/xxx/ExampleCode/adonis-vue-inertia-ssr/src.js doesn't exist
      .json
        Field 'browser' doesn't contain a valid alias configuration
        /Users/xxx/ExampleCode/adonis-vue-inertia-ssr/src.json doesn't exist
      .wasm
        Field 'browser' doesn't contain a valid alias configuration
        /Users/xxx/ExampleCode/adonis-vue-inertia-ssr/src.wasm doesn't exist
      as directory
        /Users/xxx/ExampleCode/adonis-vue-inertia-ssr/src doesn't exist

webpack 5.74.0 compiled with 1 error and 1 warning in 1447 ms

Is it possible to use the SSR feature programatically?

I am sorry to opening this as an issue! but its really important to have the SSR feature as optional for some pages. like some pages is not require SSR. On the other hand very few pages are required to Render on server side for SEO. I hope you understand my question.

So if its possible to enable SSR mode only to some certain pages please share how to do it. i tried by getting the route url by accessing CTX from the const ctx = HttpContext.get() but failed.

There seems to be an error in the readme file

In Advanced block react code like loss return

import React from 'react';
import ReactDOMServer from 'react-dom/server';
import { createInertiaApp } from '@inertiajs/inertia-react';

export default function render(page) {

 //It seems that the `return` is missing
  createInertiaApp({
    page,
    render: ReactDOMServer.renderToString,
    resolve: (name) => require(`./Pages/${name}`),
    setup: ({ App, props }) => <App {...props} />,
  });
}

If auth.attempt fails, a response is not a valid Inertia response

I'm trying to use await auth.attempt(email, password); in my login controller. If authentication fails, adonis sends automatically a response, which is plain json and therefore a popup window appears saying "All Inertia requests must receive a valid Inertia response, however a plain JSON response was received."

It seems that for some reason the automatic response removes the "X-Inertia: true" -header.

I've got a failing authentication working by using try-catch and in catch:

session.flash({
    errors: {message: error.message}
});
return response.redirect().back();

webpack loader for react

Hi.

After the new SSR update, I've been getting this error while trying to run React with SSR

ERROR in ./resources/js/ssr.js 10:31
Module parse failed: Unexpected token (10:31)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
|     render: ReactDOMServer.renderToString,
|     resolve: (name) => require(`./Pages/${name}`),
>     setup: ({ App, props }) => <App {...props} />,
|   })
| }

Any idea what "loader" it's missing? Couldn't find anything appropriate on webpack docs.

Could not determine executable to run

I installed Inertia-Adonis as mentionned on the README, but when it comes to run ssr:watch, it print this:

ฮป node ace ssr:watch
npm ERR! could not determine executable to run

npm ERR! A complete log of this run can be found in:
npm ERR!     REDACTED.log

Manually installing @symfony/webpack-encore made it work. I don't know if I did something wrong, but if not, it should be mentioned in the doc I think.

[Security] Workflow commitlint.yml is using vulnerable action wagoid/commitlint-github-action

The workflow commitlint.yml is referencing action wagoid/commitlint-github-action using references v2. However this reference is missing the commit bf83d2b35c4177779d047f464b48d9907f2c5201 which may contain fix to the some vulnerability.
The vulnerability fix that is missing by actions version could be related to:
(1) CVE fix
(2) upgrade of vulnerable dependency
(3) fix to secret leak and others.
Please consider to update the reference to the action.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.