Remix: middleware pattern to run code before loader on every request?

Is there a recommended pattern in Remix for running common code on every request, and potentially adding context data to the request? Like a middleware? A usecase for this might be to do logging or auth, for example.

The one thing I’ve seen that seems similar to this is loader context via the getLoadContext API. This lets you populate a context object which is passed as an arg to all route loaders.

It does work, and initially seems like the way to do this, but the docs for it say…

It’s a way to bridge the gap between the adapter’s request/response API with your Remix app

This API is an escape hatch, it’s uncommon to need it

…which makes me think otherwise, because

  • This API is explicitly for custom integrations with the server runtime. But it doesn’t seem like middlewares should be specific to the server runtime – they should just be part of the ‘application’ level as a Remix feature.

  • Running middlewares is a pretty common pattern in web frameworks!

So, does Remix have any better pattern for middleware that runs before every loader? If so, how do you use it?

Why is this javascript / css animation only working on the first of its kind and not the rest?

I am trying to get multiple different circles to do this transition, but only the first one will trigger the effect (regardless of where the rest are on the page)

javascript

let circle = document.querySelector('.circle')

circle.addEventListener('mouseenter', () => {
    if(!circle.classList.contains('hover')){
        circle.classList.add('hover');
    }
})

circle.addEventListener('mouseleave', () =>{
    if(circle.classList.contains('hover')){
        circle.classList.remove('hover');
    }
})

css

.circle {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100px;
    width: 100px;
    background: slateblue;
    border-radius: 100px;
    font-size: 1.5rem;
    color: #fff;
    cursor: pointer;
    transition: cubic-bezier(0.075, 0.82, 0.165, 1) 3s;
}

.hover {
  transform: scale(1.5);
}

html

<div class="circle">1</div>
<div class="circle">2</div>

React-the state is already updated, but when calling setstate again, the value is still the old value

If I enter a fromAmount which is larger than the current toAmount, then toAmount value is expected to become fromAmount + $1.


    const initialObj = {
      fromAmount: '',
      toAmount: '',
      comment: ''
    };
    const [itemObj, setItemObj] = useState(initialObj);

    const setItemFieldHandler = (key, value) => {
      console.log("set", key, value);
      console.log("old state: ", itemObj);
      
      const newState = {
        ...itemObj,
        [key]: value
      };
      
      console.log("new state: ", newState);
      
      setItemObj(newState);
    };


    const handleFromAmountInput = useCallback((value) => {
       setItemFieldHandler('fromAmount', value);
      //check if from amount > to amount, 
      // then set toAmount = fromAmount + 1
      if(areBothAmountsValid()) {
         const newToAmount = value + 1;
         handleToAmountInput(newToAmount);
      }
    }, [itemObj]);


    const handleToAmountInput = useCallback((value => {
      setItemFieldHandler('toAmount', value);
    }, [itemObj]);
    }

The current from-amount is 1, to-amount is 5. If I change from-amount to 10, the console log is:

set fromAmount 10
old state: 
  {
    fromAmount: 1,
    toAmount: 5,
    comment: ''
  }
new state: 
   {
    fromAmount: 10,
    toAmount: 5,
    comment: ''
  }

set toAmount 11
old state: 
  {
    fromAmount: 1,
    toAmount: 5,
    comment: ''
  }
new state: 
   {
    fromAmount: 1,
    toAmount: 11,
    comment: ''
  }

What confuses me is that, fromAmount is already set as 10, why when calling handleToAmountInput(), the fromAmount’s value is still 1.

At first, I thought it is because the setState is async, so I used setTimeOut to make handleToAmountInput() running after like 5s to test, but the issue is still the same.

Does anyone know the reason and how to solve it?

React / Typescript : pushing obj into array of object and undefined type

I’m beginnig my journey into TypeScript in React and to experiment what I’ve learn, I’ve try a simple Todo App.
Everything is working fine except ONE things !

When I’m pushing ‘newTask’
When I’m hovering ‘newTask’ here’s the hint (Google Trad from French) :

The ‘Todo | undefined ‘is not attributable to the parameter of type’ Todo ‘.
Cannot assign type ‘undefined’ to type ‘Todo’.

I guess it’s related to something here :

let [newTask, setNewTask] = useState<Todo>();

because if I type useState<any>(); I don’t have any error..

Here’s the full code :

import React, { useState } from "react";

// INTERFACES
interface Todo {
  id: number;
  text: string;
  completed: boolean;
}

export const TodoComponent = () => {
  // STATE
  const initialTodos: Todo[] = [
    { id: 0, text: "Todo 1", completed: false },
    { id: 1, text: "Todo 2", completed: true },
    { id: 2, text: "Todo 3", completed: false },
  ];

  const [todos, setTodos] = useState<Todo[]>(initialTodos);

  let [newTask, setNewTask] = useState<Todo>();

  // ACTIONS
  const handleClickOnComplete = (id: number, completed: boolean) => {
    const newTodos = [...todos];
    newTodos[id].completed = !completed;
    setTodos(newTodos);
  };

  const handleRemove = (todo: Todo) => {
    const newTodos = todos.filter((t) => t !== todo);
    setTodos(newTodos);
  };

  const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    setNewTask({
      id: todos.length,
      text: event.target.value,
      completed: false,
    });
  };

  const handleSubmitNewTodo = () => {
    const newTodos = [...todos];
    console.log(newTask, newTodos);
    newTodos.push(newTask);
    setTodos(newTodos);
  };

  return (
    <div>
      <h1>Todo App !</h1>

      <div>
        {todos.map((todo) => {
          return (
            <div key={todo.id}>
              {todo.id} - {todo.text} -{" "}
              <input
                type="checkbox"
                checked={todo.completed}
                onChange={() => handleClickOnComplete(todo.id, todo.completed)}
              />
              <button onClick={() => handleRemove(todo)}>Remove task</button>
            </div>
          );
        })}
      </div>

      <hr />

      <div>
        <input placeholder="Add todo" type="text" onChange={handleChange} />
        <button onClick={handleSubmitNewTodo}>Add todo</button>
      </div>
    </div>
  );
};

Problem is in handleSubmitTodo

Thanks for your help and advices.
Take care.

Is it possible to extract several js files out of one entry point in webpack?

I have set up webpack to generate the public directory from my development enviroment. I have several pages that are being built.
Therefore my entry configuration looks like this:

entry: {
    page_one: [one/main.js, one/index.html, ...]
    page_two: [two/main.js, two/index.html, ...]
}

This works perfectly fine. However i also want to extract some js-files that depends on some serverside renderings. Therefore i dont always have to include those. My initial aproach was to simply add the js file to my entryset. Looks like this:

entry: {
    page_one: [one/main.js, one/maybe.js, one/index.html, ...]
    page_two: [two/main.js, one/another.js, two/index.html, ...]
}

The problem is that both js files get packed into one output file. That kinda makes sense to me but is there some way to archieve my goal of exporting them both separately on the same entrypoint?

Folder structure i get:

 - public
   - one
     - index.html
     - main.js
   - two
     - index.html
     - main.js

Folder structure i want:

 - public
   - one
     - index.html
     - main.js
     - maybe.js
   - two
     - index.html
     - main.js
     - another.js

As mentioned maybe.js and another.js are there but packed into main.js but i want them to be extracted separately.

W3C HTML5 ERROR Start tag head seen but an element of the same type was already open

Start tag head seen but an element of the same type was already open.
also I got some other errors:

” Saw <?. Probable cause: Attempt to use an XML processing instruction in HTML. (XML processing instructions are not supported in HTML.) “

and

” No p element in scope but a p end tag seen. “

I have no clue how to fix them.

<!DOCTYPE html>
    <html lang="pl">
    <style>
    html, body { margin: 0; padding: 0; color: black; background-color: grey;}
    #strona { position: absolute; color: white}
    #rects { position: relative; width: 300px; height: 125px; border: 1px solid #FF0000; color: yellow; margin: 5px; padding: 2px;}
    </style>
    <head>
        <meta charset="UTF-8"/>
        <title> site</title>
    </head>
    <body>
    <div> <script>
    function clickbutton1(){
        document.getElementById("opis").innerHTML = Date();
    }
    </script>
    </div>
    
        <div id="strona">
            <h1>test</h1>
    <?php
    echo "<p>data replacement</p>";
    echo "<div id='rects'>
        <!-- starting of the function -->
    <p id='opis'> internal description </p>
    <script>
    document.getElementById('rects').onclick = clickbutton1;
    </script>
    </div>";
    ?>
    </div>
    
    
    </body>
    
    </html>```

Actionscript ( ) vs Javascript ( )

For same string actionScript’s function charCodeAt returns unicode character 13 and javascript’s function charCodeAt returns unicode character 10. Is there a reason why a line feed is returned by JS and a carriage return is returned by AS. After reading a few answers online I have come to the conclusion that both of these do not have much difference, can anyone please explain why was this change made.

Vue JS Accordion Performance with Bootstrap and B-Modal

I have a large Table. I am using Bootstrap and implementing the Accordion structure with “b-accordion”. When I want to update the data in any Row, I am experiencing an incredible loss of performance. I am using Modal to edit rows. (B-MODAL)

My table content is like this. When the row is clicked, the Accordion below opens.

Table Generate Code..

<tbody>
    <template v-for="(item, index) in pageArray">

      // Table Row
      <tr :key="`tableTr-${item.recordNo}`">
        <td :id="`accordion-${item.recordNo}-1`" v-b-toggle="`collapse-${item.recordNo}`">
          <a class="text-dark">{{ item.recordNo }}</a>
        </td>
        // Likewise the other 13 Columns.
      </tr>

      // Accordion Row
      <tr :key="`tableSubTr-${item.recordNo}`" class="subtr">
        <td colspan="14">
          <b-collapse :id="`collapse-${item.recordNo}`">
            <div class="container-fluid">
             ....
            </div>
          </b-collapse>
        </td>
      </tr>

    </template>
</tbody>

Now let’s get to the real problem. When I start the EDIT process for any Row, Vue Developer Tools draws a performance like the one below. The low performance ones are all because of the Model I opened.

enter image description here
enter image description here

B-MODAL I made as a Component
props: { thisObject: Object }
<b-modal v-model=”isModal” centered hide-footer hide-header size=”xl” @hide=”$emit(‘closeModal’, true)”>
{{thisObject}}

Translatepress breaking javascript. Adds defer to script tags automatically

I’m using translatepress to translate my company’s website, but it’s causing one of our calculators written in javascript to not load. I’ve found it’s adding “defer” to a bunch of our tags. Any ideas on how to prevent this from happening? I’ve tried disabling “Fix missing dynamic content” and “Disable dynamic translation” but none have worked.

Passport.js – req.isAuthenticated is not a function

I’m new to node and express and node and I’m building an authentication feature with passport.js. In my routes I’m using a middleware function called “checkNotAuthenticated” to check if the user is not authenticated, but I’m getting this error: “TypeError: req.isAuthenticated is not a function”

What could the problem be here?

My routes:

const express = require('express')
const router = express.Router()
const bcrypt = require('bcrypt')
const passport = require('passport')
const flash = require('express-flash')
const session = require('express-session')
const methodOverride = require('method-override')

const User = require('../models/user.model')
const initializePassport = require('../passport-config')
initializePassport(passport)

const app = express()

app.use(flash())
app.use(session({
  secret: process.env.SESSION_SECRET,
  resave: false,
  saveUninitialized: false
}))
app.use(passport.initialize())
app.use(passport.session())
app.use(methodOverride('_method'))

/* Middleware function to check if user is authenticated */
function checkNotAuthenticated(req, res, next) {
  if (req.isAuthenticated()) {
    return res.redirect('/')
  }
  next()
}

/* ------- Routes ------- */
/* Create new user */
router.post('/register', checkNotAuthenticated, async (req, res) => {

  /* Check if the email isn't already taken */
  const emailIsTaken = await User.findOne({email: req.body.email})
  if (emailIsTaken) return res.status(500).send('Email already used')

  try {
    const hashedPassword = await bcrypt.hash(req.body.password, 10)

    const user = new User({
      name: req.body.name,
      password: hashedPassword,
      email: req.body.email,
      title: req.body.title,
      about: req.body.about
    })

    user.save()

    res.send('Success - User created')

  } catch (err) {
    res.status(500).send(err)
  }

})

/* Login user */
router.post('/login', checkNotAuthenticated, passport.authenticate('local', {
  successRedirect: '/',
  failureRedirect: '/login',
  failureFlash: true
}))

/* Logout */
router.delete('/logout', (req, res) => {
  req.logOut()
  res.redirect('/login')
})

module.exports = router

passport-config.js:

const User = require('./models/user.model')
const LocalStrategy = require('passport-local').Strategy
const bcrypt = require('bcrypt')

function initializePassport(passport) {

    const authenticateUser = async done => {

        /* Check if there's a user account created with that email */
        const userFound = await User.findOne({email: req.body.email})
        if (!userFound) return done(null, false, {message: 'Cannot find user with that email'})
        
        /* Validate password */
        try {
            const checkPassword = await bcrypt.compare(req.body.password, userFound.password)

            if (checkPassword) {
                return done(null, userFound)
            } else {
                return done(null, false, {message: 'Incorrect password'})
            }
            
        } catch (err) {
            return done(err)
            
        }
    }

    passport.use(new LocalStrategy( { usernameField: 'email' }, authenticateUser) )

    passport.serializeUser(done => { done(null, userFound.id) })
    passport.deserializeUser(done => { done(null, userFound) })
}

module.exports = initializePassport

Full error:

TypeError: req.isAuthenticated is not a function
    at checkNotAuthenticated (/home/German/Desktop/ger/code/projects/helpr/helpr-back/routes/users.route.js:27:11)
    at Layer.handle [as handle_request] (/home/German/Desktop/ger/code/projects/helpr/helpr-back/node_modules/express/lib/router/layer.js:95:5)
    at next (/home/German/Desktop/ger/code/projects/helpr/helpr-back/node_modules/express/lib/router/route.js:137:13)
    at Route.dispatch (/home/German/Desktop/ger/code/projects/helpr/helpr-back/node_modules/express/lib/router/route.js:112:3)
    at Layer.handle [as handle_request] (/home/German/Desktop/ger/code/projects/helpr/helpr-back/node_modules/express/lib/router/layer.js:95:5)
    at /home/German/Desktop/ger/code/projects/helpr/helpr-back/node_modules/express/lib/router/index.js:281:22
    at Function.process_params (/home/German/Desktop/ger/code/projects/helpr/helpr-back/node_modules/express/lib/router/index.js:335:12)
    at next (/home/German/Desktop/ger/code/projects/helpr/helpr-back/node_modules/express/lib/router/index.js:275:10)
    at Function.handle (/home/German/Desktop/ger/code/projects/helpr/helpr-back/node_modules/express/lib/router/index.js:174:3)
    at router (/home/German/Desktop/ger/code/projects/helpr/helpr-back/node_modules/express/lib/router/index.js:47:12)

my javascript loop triggeres all 12 data-attributes at once

so i have been trying to make a music playlist program that, and i have been trying to make it trigger each song independantly(just like how all music players do) but my script seems to work only when i have only one song in my html, so when i added 12 songs and ordered them with data-attribute and then tried to click the button nothing happened and then i tried to use console.log to check what happened and apparently all 12 songs got triggered at once
here is my javascript
`const songs = document.querySelectorAll(“[data-songs]”);
const icons = document.querySelector(“#icon”);

`
songs.forEach((song) => {
  icon.addEventListener("click", function () {
    console.log(song);
    //put code of icon here
    if (mySong.paused) {
      mySong.play();
      icon.src = "/images/pause.png";
    } else {
      mySong.pause();
      icon.src = "/images/play.png";
    }
  });
});
`

and here is my html


    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <link rel="stylesheet" href="/css/styles.css" />
        <link
          rel="stylesheet"
          href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
        />
        <link
          rel="stylesheet"
          href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"
        />
        <title>Music App</title>
      </head>
      <body>
        <div class="music-container">
          <div class="music-header">
            <i class="fa fa-angle-left"></i>
            <div class="title">
              <p>My Music</p>
            </div>
            <i class="fa fa-search"> </i>
          </div>
          <div class="music-playlist">
            <div class="music-menu text-center">
              <div class="menu">
                <ul>
                  <li><a href="#">Songs</a></li>
                  <li><a href="#">Albums</a></li>
                  <li><a href="#">Artist</a></li>
                  <li><a href="#">Generes</a></li>
                </ul>
              </div>
            </div>
            <div class="music-box">
              <div class="music-info">
                <div class="music-img">
                  <img src="images/Filosofem.jpg" alt="" />
                </div>
                <div class="music-name">
                  <h6>Single Song Title</h6>
                  <audio id="mySong" data-songs="1">
                    <source src="/music/a.mp3" type="audio/mp3" />
                  </audio>
                  <p>Single name and music director</p>
                </div>
                <img src="/images/play.png" id="icon" style="padding-right: 20px" />
              </div>
              <hr />
              <div class="music-info">
                <div class="music-img">
                  <img src="images/Filosofem.jpg" alt="" />
                </div>
                <div class="music-name">
                  <h6>Single Song Title</h6>
                  <audio id="mySong" data-songs="2">
                    <source src="/music/b.mp3" type="audio/mp3" />
                  </audio>
                  <p>Single name and music director</p>
                </div>
                <img src="/images/play.png" id="icon" style="padding-right: 20px" />
              </div>
              <hr />
              <div class="music-info">
                <div class="music-img">
                  <img src="images/Filosofem.jpg" alt="" />
                </div>
                <div class="music-name">
                  <h6>Single Song Title</h6>
                  <audio id="mySong" data-songs="3">
                    <source src="/music/c.mp3" type="audio/mp3" />
                  </audio>
                  <p>Single name and music director</p>
                </div>
                <img src="/images/play.png" id="icon" style="padding-right: 20px" />
              </div>
              <hr />
              <div class="music-info">
                <div class="music-img">
                  <img src="images/Filosofem.jpg" alt="" />
                </div>
                <div class="music-name">
                  <h6>Single Song Title</h6>
                  <audio id="mySong" data-songs="4">
                    <source src="/music/d.mp3" type="audio/mp3" />
                  </audio>
                  <p>Single name and music director</p>
                </div>
                <img src="/images/play.png" id="icon" style="padding-right: 20px" />
              </div>
              <hr />
              <div class="music-info">
                <div class="music-img">
                  <img src="images/Filosofem.jpg" alt="" />
                </div>
                <div class="music-name">
                  <h6>burzum</h6>
                  <audio id="mySong" data-songs="5">
                    <source src="/music/e.mp3" type="audio/mp3" />
                  </audio>
                  <p>Single name and music director</p>
                </div>
                <img src="/images/play.png" id="icon" style="padding-right: 20px" />
              </div>
              <hr />
              <div class="music-info">
                <div class="music-img">
                  <img src="images/Filosofem.jpg" alt="" />
                </div>
                <div class="music-name">
                  <h6>Single Song Title</h6>
                  <audio id="mySong" data-songs="6">
                    <source src="/music/f.mp3" type="audio/mp3" />
                  </audio>
                  <p>Single name and music director</p>
                </div>
                <img src="/images/play.png" id="icon" style="padding-right: 20px" />
              </div>
              <hr />
              <div class="music-info">
                <div class="music-img">
                  <img src="images/Filosofem.jpg" alt="" />
                </div>
                <div class="music-name">
                  <h6>Single Song Title</h6>
                  <audio id="mySong" data-songs="7">
                    <source src="/music/g.mp3" type="audio/mp3" />
                  </audio>
                  <p>Single name and music director</p>
                </div>
                <img src="/images/play.png" id="icon" style="padding-right: 20px" />
              </div>
              <hr />
              <div class="music-info">
                <div class="music-img">
                  <img src="images/Filosofem.jpg" alt="" />
                </div>
                <div class="music-name">
                  <h6>Single Song Title</h6>
                  <audio id="mySong" data-songs="8">
                    <source src="/music/h.mp3" type="audio/mp3" />
                  </audio>
                  <p>Single name and music director</p>
                </div>
                <img src="/images/play.png" id="icon" style="padding-right: 20px" />
              </div>
              <hr />
              <div class="music-info">
                <div class="music-img">
                  <img src="images/Filosofem.jpg" alt="" />
                </div>
                <div class="music-name">
                  <h6>Single Song Title</h6>
                  <audio id="mySong" data-songs="9">
                    <source src="/music/i.mp3" type="audio/mp3" />
                  </audio>
                  <p>Single name and music director</p>
                </div>
                <img src="/images/play.png" id="icon" style="padding-right: 20px" />
              </div>
              <hr />
              <div class="music-info">
                <div class="music-img">
                  <img src="images/Filosofem.jpg" alt="" />
                </div>
                <div class="music-name">
                  <h6>Single Song Title</h6>
                  <audio id="mySong" data-songs="10">
                    <source src="/music/j.mp3" type="audio/mp3" />
                  </audio>
                  <p>Single name and music director</p>
                </div>
                <img src="/images/play.png" id="icon" style="padding-right: 20px" />
              </div>
              <hr />
              <div class="music-info">
                <div class="music-img">
                  <img src="images/Filosofem.jpg" alt="" />
                </div>
                <div class="music-name">
                  <h6>Single Song Title</h6>
                  <audio id="mySong" data-songs="11">
                    <source src="/music/k.mp3" type="audio/mp3" />
                  </audio>
                  <p>Single name and music director</p>
                </div>
                <img src="/images/play.png" id="icon" style="padding-right: 20px" />
              </div>
              <hr />
              <div class="music-info">
                <div class="music-img">
                  <img src="images/Filosofem.jpg" alt="" />
                </div>
                <div class="music-name">
                  <h6>Single Song Title</h6>
                  <audio id="mySong" data-songs="12">
                    <source src="/music/m.mp3" type="audio/mp3" />
                  </audio>
                  <p>Single name and music director</p>
                </div>
                <img src="/images/play.png" id="icon" style="padding-right: 20px" />
              </div>
            </div>
          </div>
          <div class="music-play">
            <div class="play-image">
              <img src="images/Filosofem.jpg" alt="" />
            </div>
            <div class="play-controls">
              <div class="controls">
                <div class="song-name">
                  <h5>Dunkelheit</h5>
                  <p>Burzum</p>
                </div>
                <div class="play-icon">
                  <i class="fa fa-step-backward"> </i>
                  <i class="fa fa-play"> </i>
                  <i class="fa fa-step-forward"> </i>
                </div>
              </div>
              <div class="music-progress">
                <div class="progress">
                  <div class="progress-bar"></div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <script src="/Script/jquery-3.6.0.min.js"></script>
        <script src="/Script/script.js"></script>
      </body>
    </html>
    ```

Betheme mobile hamburger menu

so I have a page on my website that use anchor links that can be accessed in menu but on mobile when I click on a category (anchor link) the menu isn’t closing automatically, I need to close manually by pressing on hamburger menu again.
This this is all my code from menu.js:

https://pastebin.com/hTL6wx2Q

This doMenu function :


            if( ( window.innerWidth >= options.mobileInit ) || ( ! options.responsive ) ){
                
                // desktop --------------------------------

                $( '> li, ul:not(.mfn-megamenu) li', menu ).hover(function() {
                    
                    $(this).stop(true,true).addClass( options.hoverClass );
                    
                    $(this).children( 'ul' ).stop(true,true).fadeIn( options.delay );
                    
                    
                }, function(){
                    
                    $(this).stop(true,true).removeClass( options.hoverClass );
                    
                    $(this).children( 'ul' ).stop(true,true).fadeOut( options.delay );  
                    
                });
                
            } else {

                // mobile ---------------------------------
                
                $( 'li', menu ).unbind('hover');
                
                $( 'li > .menu-toggle', menu ).off('click').on('click', function(){
    
                    var el = $(this).closest('li');
                    
                    if( el.hasClass( options.hoverClass ) ){
    
                        el.removeClass( options.hoverClass )
                            .children('ul').stop(true,true).fadeOut( options.delay );           
                        
                    } else {
        
                        el.addClass( options.hoverClass )
                            .children('ul').stop(true,true).fadeIn( options.delay );    
    
                    }
                    
                });
                
            }
            
        };

i18next will not load custom namespace

I have an instance of i18next running as it should if I include the translations inside the init:


i18next.use(httpAPI).init({
    lng: language,
    resources: {
      en: {
        translation: {
          "html1": "foo! ",
          "html2":"bar",
        }
      },
      de: {
        translation: {
          "html1": "de-foo",
          "html2":"de-bar",
    
        }
      }
  }
})

However, I expect to be expanding my translations, and placing them in the init would become unwieldy. So I would like to split them into multiple files. I have read about using i18next.http-backend. So when I re-write my init to include the backend my init looks like this:

i18next.use(httpAPI).init({
    lng: language,
    backend:{ loadPath: '/locales/de-DE/translate.json'}
})

the translate.json file looks like this:

{"translation": {
  "html1": "backend-de-foo",
  "html2": "backend-de-bar",
}}

My main script where I am calling the i18next is in the parent directory along with my locale folder.

It does not appear to be reading from the backend loadpath, as I am not getting any translations from it. Am I missing something from i18next or is my translate file not structured properly?

How can i divide the string into 496 rows and subdivide them according to heading in javascript

ptr[97,186,286,380,433,496]
strpar["BRACKENRIDGE: This is March the 7th, 2018. I'm R. Douglas Brackenridge, Professor Emeritus at Trinity University. With me here at Trinity is Jes Neal who is the Trinity University archivist. And we will be interviewing Betty Meadows, who is a Trinity graduate. Now, what years? You came in--? MEADOWS: I came in 1966 and left in 1970. BRACKENRIDGE: Okay, from 1966 to 1970. And you played tennis at Trinity. Is that correct? MEADOWS: I did. BRACKENRIDGE: Did you play any other sports? MEADOWS: No. BRACKENRIDGE: With that bit of introduction, let me just start back and say, how did you end up at Trinity? MEADOWS: [laugh] BRACKENRIDGE: How did you come to Trinity? And did tennis have anything to do with it when you came? MEADOWS: No. No, no. And I hope I'm going to be helpful, but my memory isn't great about all that. But anyway, I came to Trinity because I'm a Presbyterian and I've always wanted to go to a Presbyterian college. And we lived out in West Texas in a little town called Monahans, which is where I learned to play tennis. And when we moved to San Antonio, wow, I was able to just drive across town and go to college. But I stayed in the dorm; I didn't stay in my parents' home or in my home. But it's a school I always wanted to go to because I heard of its reputation. It did have a tennis team, but that's not really why I came. I came for academics. I came because it was a Presbyterian school. BRACKENRIDGE: And it would have been like maybe your (SP) minister that had any influence on you? MEADOWS: No, no. I was going to be a school teacher. My parents--my dad's a principal, my mother's a teacher, my brother's a teacher. I came to be an education major. Had no intention ever of working in a church, ever. And that call from God didn't come until 10 years later. It came in 1980, and it was a really powerful call. So I left--I went to seminary. But it was not my intention. BRACKENRIDGE: Where did you go? To Austin? MEADOWS: Austin Seminary. BRACKENRIDGE: Just an aside, did you know Bill Walker from Grand Falls? MEADOWS: No. BRACKENRIDGE: (INAUDIBLE) Monahans. Grand Falls was pretty close to Monahans. MEADOWS: It is. Yeah. BRACKENRIDGE: Yeah. But he was born and raised in Grand Falls. MEADOWS: Oh my goodness. BRACKENRIDGE: And he said there's no Grand Falls there. MEADOWS: No, there's no Grand Falls. BRACKENRIDGE: So then what did you major in, Betty? MEADOWS: Elementary education. And I took 21 years of Latin. BRACKENRIDGE: Wow. MEADOWS: Yeah, wow. BRACKENRIDGE: How old were you when you really left Monahans? MEADOWS: Sixteen. BRACKENRIDGE: Okay, so you really grew up there. MEADOWS: I did. BRACKENRIDGE: And again, we're focusing on the athletic part, but did you play tennis and that out there? MEADOWS: I did, I did. I started playing tennis in the seventh grade. And we called it junior high in those days. I started in seventh grade tennis. And the reason I started is we didn't have a girls tennis team and they were trying to get players together and the coach said, "You want to learn?" And he sent me to a tournament in three weeks. I had no idea what I was doing. I had no idea how to hit a ball. But I went to the tournament and had a riot. And we didn't win anything because nobody could hit, but at least the school was able to put in a tennis team, a doubles team. And from that point, it just kind of--it was in my blood. I loved it. And I got better and better. And so I played all the way through high school and a good bit through college. In fact, when I graduated, Doug, I actually coached tennis on the side in San Antonio for a number of years, and loved it. I taught boys and girls how to play. And then when I moved to middle school and started teaching sixth, seventh, and eighth graders, I was the tennis coach after school. And I loved it. I mean, I just loved it. It was a great way to work with kids and give them some support and teach them a skill and teach them also what is etiquette and what is tennis etiquette. And if you threw your racket or said curse words, I withdrew you from the tournament and said, "That's tough." [laugh] Anyway, but I just loved it. Tennis was a great--get you in the sun, got you exercise, got you with other people. Competitive but not too competitive. I mean, it's competitive enough. So, it really became a way of life. And that went into racquetball and then that went into running. And now I just go to the Y during the day. So it's just an active lifestyle. BRACKENRIDGE: Back then, what were your feelings about the fact that that women didn't have much opportunities to do these? That the men were in all these sports. Was that an issue when you were younger or was that not something you really thought much about? MEADOWS: Well, I didn't think much about it because in high school, we had a woman's basketball team. We had a woman's volleyball team. Now we had a woman's tennis team. So I don't think I thought much about it. It wasn't a plus or minus. It was just I wanted to play (INAUDIBLE). BRACKENRIDGE: Did you feel like there was much more interest in the men's sports and the women's were kind of considered just a (INAUDIBLE)? MEADOWS: Always. Always. Always. Because the men could run the whole floor in basketball. They (INAUDIBLE) football. BRACKENRIDGE: The basketball, was it still the stationary, where you couldn't--you didn't play full court? MEADOWS: You could only play half court. BRACKENRIDGE: Right. Well, they were still doing that in the early 1970s. They were still playing basketball that way. Right. MEADOWS: Yeah. The women were thought to be very brittle, very fragile. (INAUDIBLE). And I didn't think much about that either, really. I really didn't think much about that. I just knew that I liked to play tennis, and so I played tennis. And you could be as rough or you could play singles or you could play doubles and you could have mixed doubles. Yeah, yeah. I don't think I thought much about the fact that women didn't have the money. Because Trinity wasn't a big athletic school. BRACKENRIDGE: No, no. MEADOWS: It really wasn't. If I had been going--gone to University of Texas or Alabama or Georgia where you would have seen tons of money put into men's sports, it might have hit me differently. But sports were just kind of an add-on at Trinity. It wasn't-- BRACKENRIDGE: Right. Well, particularly--but tennis was the one big thing. MEADOWS: It was. It was. BRACKENRIDGE: Tennis--not in your days so much, but very shortly thereafter, that was the one sport that women could get scholarships in. And it always got high priority and publicity and an interest, where the other sports were in a definitely lower category. Tennis was a much bigger thing. MEADOWS: Yeah. So when I was there, I don't remember a lot of money being put into scholarships for sports. BRACKENRIDGE: No, there wasn't any. Of course, there wasn't any women's team then, either. So tell me, who helped you or how did you do it? Do you remember? MEADOWS: I am guessing that when I registered and I asked, "When does tennis start and where can I show up?"--and I showed up. I'm sure I just went down to the courts with my racket and talked to the coach. BRACKENRIDGE: You mean the coach Clarence Mayberry? It wasn't Shirley Rushing? Would she have anything to do with that then? MEADOWS: Shirley Rushing, I can't remember when she started. Was she there in 1966? BRACKENRIDGE: Oh, she was there in 1962. She was there in 1960. MEADOWS: Okay, because it was a female coach, so it had to be Shirley Rushing. BRACKENRIDGE: Yeah, that's who would have--yeah, because they didn't have any female coaches. There weren't any listed. She was the only woman in the PE department. MEADOWS: Okay. She was our coach. BRACKENRIDGE: Okay. [laugh] All right. I think that--okay. MEADOWS: She showed up, too. We showed up; she showed up. And we traveled to tournaments. We would all jump in the car. BRACKENRIDGE: I know she went to the tournament with you. MEADOWS: Yeah, she did. She did. BRACKENRIDGE: I guess what I'm asking you--was there any, quote, "coaching" going on or was it just you showed up and played? MEADOWS: No. There was no coaching. We just all got out on the courts and played. We just played our hearts out. BRACKENRIDGE: And then how did you decide who's going to play number one and number two? Would she have something to do with that or did you all--? MEADOWS: Well, we all knew who was number one. That was Emilie Burrer. We all knew that. BRACKENRIDGE: Well, but this is before Emilie Burrer. MEADOWS: Oh, before Emilie? BRACKENRIDGE: 1967, there's no Emilie Burrer there. MEADOWS: When did Emilie come? BRACKENRIDGE: 1968 and 1969. MEADOWS: Oh gosh, I forgot. I don't know who was first. BRACKENRIDGE: That's what I'm saying. You have Mary McLean, Ginger Parker (SP), Sally Goldschmeding, Betty Meadows and Elise Folden (SP) for 1967. So that's why this is so hard to figure out, because we didn't have all these formalities. We didn't have Trinitonian articles about it. And then even Shirley, she doesn't remember everything. I mean, I don't remember--you ask me about what I did in 1967 or 1968, I couldn't tell you. I'd have to go back and try to research it. [NEAL]: I wonder, were Mary McLean and Ginger Parker kind of the number one spots? Because (INAUDIBLE)-- BRACKENRIDGE: Well, I think Mary McLean was a noted player. I mean, I think she was-- [NEAL]: Yeah, she was in the Beaumont tennis tournament. And this is all in 1966. She gained, what is it, single competition, she went to the semifinals. BRACKENRIDGE: Yeah. That Mary McLean apparently was an outstanding player. MEADOWS: She was. BRACKENRIDGE: But you just played with each other, right? And you just played against each other? MEADOWS: Yeah, we weren't coached. We just played with each other. And those who wanted to play singles played singles. Those who liked doubles played doubles. BRACKENRIDGE: And what about schedule? Did you just go to tournaments? MEADOWS: No, we worked out almost every day, is what I remember. BRACKENRIDGE: No, but I mean, did you play other teams, so like in San Antonio? MEADOWS: Oh, yeah. We would go to tournaments. But we basically played with each other at Trinity. I don't remember playing any (INAUDIBLE)-- BRACKENRIDGE: You didn't play SAC [San Antonio College] or Saint Mary's [University] or Incarnate Word? MEADOWS: (INAUDIBLE) BRACKENRIDGE: See, they maybe--not even have a team then. Because there wasn't much going on in that (INAUDIBLE). MEADOWS: Yeah, I don't remember that. I don't remember ever playing another school in San Antonio. I know that we practiced almost every day. I remember walking back to the dorm with my tennis clothes on and I'd shower and I'd go to supper, or study, or whatever. But I don't remember--hmm. (INAUDIBLE) BRACKENRIDGE: Well, did you get to play on the upper courts? On the varsity courts? Or did you go off campus to practice? MEADOWS: No, we played on the varsity courts. We weren't off campus at all. We would play always on campus. BRACKENRIDGE: Okay, but by your time, there weren't tennis courts down by the Sams Center, were there? MEADOWS: No. BRACKENRIDGE: No, they were there by 1970. They were there--1969 or 1970, they built those, because the NCAA was coming for the men's tournament there. But we've read or other tennis players have said that a lot of times it was hard to get on the courts because the men used them a lot and the women just had to grab whatever time they could get to play on. But you don't remember ever having a real problem about that? MEADOWS: Yeah, I don't remember that. I really don't. My memory is [laugh] that we played--there were probably certain hours that the courts were available, I guess. I don't remember. I don't remember jostling around. But my memory is it was a little unorganized. We were just out there enjoying the sport and loving it, making friends, going to tournaments, and going to school. I mean, it wasn't a money thing. It wasn't real organized. We weren't coached. BRACKENRIDGE: And did they like pay for these uniforms? Did they pay for anything, where you're wearing these outfits? No? The white dresses and-- [PERSON]: (INAUDIBLE) MEADOWS: I don't remember them paying for any of that. BRACKENRIDGE: Because now, when you traveled, did Trinity pick up any of the costs? MEADOWS: They did. All travel. BRACKENRIDGE: That would be through the PE department, where you would be getting that money. MEADOWS: Right. The food, expenses, the gasoline, whatever. Right. BRACKENRIDGE: And they paid for your food? MEADOWS: And the hotel. Oh, sure. Whatever our expenses are. And I remember we used to take turns driving. We would all pile into these big cars and we would just all take turns driving until we got there, and then we'd play ball, and then we'd all drive back. BRACKENRIDGE: And most of those would be in Texas, right? You weren't driving out of state? MEADOWS: Right. BRACKENRIDGE: Of course Texas is a big state. You could be driving up in the Panhandle, right, if there was a meeting up there. MEADOWS: Right, right. BRACKENRIDGE: And I noticed--well, I didn't bring that picture, but one of the teams was showing that they got some fancy coats. I don't remember--I thought I--that might have been a little bit later that they had some jackets that they bought, that they made or something. But that might have been after your time. MEADOWS: Yeah, I don't have any of that. No. BRACKENRIDGE: But my assumption is that Shirley Rushing was arranging all this. MEADOWS: That's my memory. BRACKENRIDGE: They often call her the sponsor. They don't call her the coach. They call her the sponsor. So I'm assuming that that's what that role meant more. Because she was a full-time PE teacher and that; she wouldn't have a lot of time to do a lot of coaching. And I don't know that tennis was her first sport. I don't think Shirley ever--I don't know that that was her sport, anyway. MEADOWS: I don't think so. Yeah. I think she was kind to organize it and to take us to tournaments and let us play. But it was for me maybe extra-intramural, extramural, whatever. BRACKENRIDGE: Jim Potter, was he there by the time you were there as intramural, do you remember? He didn't really come until like 1967 or 1968. But you weren't really involved that much with intramurals. MEADOWS: No, no, just--no. BRACKENRIDGE: It was just more the tennis, okay. MEADOWS: Just tennis. BRACKENRIDGE: So again, just that I make sure I understand, more or less your memory is that it was at registration that you were asking about tennis and somebody told you where to go, or whatever, to meet with somebody, and that's where some of the women got together, and that Shirley was the one that kind of organized it. MEADOWS: Right. She organized it, but my memory is the kindness of Emilie Burrer. Emily Burrer would work with you on any skill, any forehand, any backhand, any serve that was giving you trouble. She was just a really wonderful teammate. And she would give her time to coach any of us because there was no coach. BRACKENRIDGE: Okay, well, see, that's something that I had no idea about. And it was her winning that kind of elevated the women's tennis. MEADOWS: Yes, she was a dynamite. She was awesome. Yeah. BRACKENRIDGE: And so when she came, it was still pretty much the same thing, right? That you didn't really have a coach. MEADOWS: No. BRACKENRIDGE: And it was Shirley who would be the person who would be doing whatever was needed to be done. Is that pretty much your memory? MEADOWS: That's my memory, right. Maybe Shirley's role was to get us registered into conferences, to send the entry fee to get us there, house us, bring us back. More of an administrator, I'm guessing, for us, yeah. (INAUDIBLE) BRACKENRIDGE: One of the things that that we have--this is a kind of a side project that--you know, they have this kind of Hall of Fame for athletes here at Trinity, and I think--we think she ought to be recognized for all that she did. See, the kind of things you're talking about, nobody has any idea that that she would be involved in any way about helping. And we've got other stories where the people are saying the same kind of thing that you're saying. Oh, that she helped us and she did this and she did that. So do you remember any other kind of contact with Shirley or you had any classes, or not particularly? MEADOWS: No. It's a long time ago! BRACKENRIDGE: I know it is. I know. If you want to chime in here now--the only thing that I would ask again was your impression of--what was the feeling amongst the other students about women's tennis? Was it a big thing or a little thing or nobody paid much attention to it? Do you have any memories of that or was that not something that was of a concern to all of you? MEADOWS: I don't have any impression that it mattered to the student body. The impression I have is that we enjoyed playing and we enjoyed being with each other. We enjoyed just the athleticism. But it wasn't a big thing for the school. That's my impression. I mean, there weren't accolades, or Emily wasn't held up for all the wins she's made. Because she was our star when she got there. Yeah. I think we played because we loved the sport. We played because it was just an exhilarating feeling to go work out and come back and study. It just was great to work out all the tension through classes, and pressure. I think that was true for all of us. It wasn't awards or it was important to the school or we were in anyone's heyday of--you know. BRACKENRIDGE: Were you aware of like what later became the AIAW? When you went to these tournaments, there were different sponsors. There were invitational tournaments where the school would invite, or this larger women's group. I don't think that was as well organized when you were playing. It was more in the 1970s that it became-- MEADOWS: Right, right. I preceded that. BRACKENRIDGE: One more question. Was there any difference that you got out of playing tennis--did that add to your experience at Trinity in your education? Were there any values you see getting out of that? What would be your mindset on that? MEADOWS: I think sports are good for all people. It's a holistic kind of thing. You learn how to win well. You learn how to lose well. You learn how to compete. You learn how to care for your opponent. You learn how to treat somebody who you just beat. You learn how to work with your classmates and your other team members who lost and didn't think they were going to. It's a whole lot of life skill that comes together in sports. And winning is not the major thing, although it's important. But I think it was the whole roundedness of being an individual. That life isn't just about good grades. It's not just about always winning. But it's about how we get along with each other in the midst of all that stuff. So the life skills were, "I'm never going to be number one, and that's okay with me. I don't have to be number one in everything. I'm a good student. I'm gonna be really good at certain things. But other things I'm gonna be the mediocre." And that's a good thing to know. And mediocre is just fine. I'm never gonna be Emilie Burrer or these other people. But I can learn from them. And to be around an Emily who was so gracious with her time and her technique showed me how to graciously be a number one in anything. Her modeling was wonderful, so that you know later in life if you're number one in anything, you share what you know. It's not all about you. So I think sports is a great teacher. It's a great teaching moment for a human being. BRACKENRIDGE: That's wonderful. That's very eloquent. So what have you done in later life, Betty? You taught. You taught in the public schools? MEADOWS: I did. I taught 10 years in public school. And then I went to seminary and had a small church out in West Texas that I just adored, and wanted to be a pastor forever. But God always has God's ways. And so then I went to Atlanta where I was on the presbytery staff. So then I began to shepherd 110 churches in evangelism as an associate exec. I did that seven years. And I thought, "Oh, this is great. I could just stay here." "No," God said. "No." So then I went to Louisville as the exec. And I was the exec, the top administrative person, for 16 years, in Louisville, Kentucky, for Mid-Kentucky Presbytery. And I thought, "Oh, this is great. I'll retire from here." God said no. So then God brought me to Charlotte where I'm a transitional--general presbyter. So I've shepherded a presbytery that was broken and there was no trust. Lack of transparency. Racial issues, theological issues. And my time here is coming to an end, and we have--by God's grace and a lot of people volunteering, we've been able to heal this presbytery. God has worked with us on that. And now the new person is coming May 1 and I retire! And it has been a wonderful, wonderful journey of--thought I was going to teach forever. No. Thought I was going to be a pastor of a church forever. No. Thought I would be a general presbytery. No. I mean, every time I said, "God, this is it," God said, "Oh, no, it isn't." But I am going to retire. BRACKENRIDGE: But you're not going to stop. MEADOWS: I'm not going to stop , no. I'm going to go back--before seminary, I was teaching school, but I was working with battered women and pregnant teens. And so all I want to do is go back to hands-on street work, just volunteering my time for the sake of somebody else. And I don't need a title, don't need an office, don't need a salary to do that. And I don't need to go to another country. There's enough need in my backyard here in Charlotte. So it's come full circle, Doug Brackenridge. Full circle. So I retire from professional ministry but never from ministry. BRACKENRIDGE: Well, I guess when they say you're honorably retired, that leaves a lot of room for activity, doesn't it? MEADOWS: Tons of room. Tons of room. Yeah. BRACKENRIDGE: So it seems like--I know that there's much more involved in a ministerial call, but it seems like what you said so eloquently about tennis are exactly what you had to deal with in becoming a Presbyterian, a woman pastor, and dealing with all these issues and working with people and having to solve problems. That some of those things you learned a bit during your college years probably carried over. MEADOWS: It did. It did. I mean, what we can learn in athletics really carries through life. And also keeps our bodies healthy so that--my mother's about to turn 100, and I may follow her and I may not. We'll see. BRACKENRIDGE: Well, I was trying to think--we did meet one time. I don't remember whether it was at a general assembly. But it seemed to me we met--there was something else going--I mean, I was in Charlotte doing some research and maybe I met you at some event there, but we did meet. I remember meeting. MEADOWS: We did. I remember that, too. It was a while back. I don't remember--but it was a while back. But that's right; I remember. And I remember your class. I remember your--you had the first religion class. And I remember this strange movement inside of me one day when you were teaching. And I thought, "What is that?" And I was being drawn into ministry. Because it took 10 more years for that seed to develop roots and sprouts. But it started in your class, Doug Brackenridge. BRACKENRIDGE: Well, sometimes you don't ever hear much from students in the past, but sometimes you find, though, that many students have never been introduced to what you'd call the academic study of religion. They've never had that. And it comes as a shock to them. I know it did to me when I was in college. But that it's liberating if it's something that you can view as positive and not negative. You learn that there's something more to learn that you don't know, and you kind of move out. And I think that's one of the things that a liberal arts school should do for somebody. Not to indoctrinate them, but to open up some doors or some windows that they can look through and say, "This is the way I'm gonna follow, but I'm aware there are other ways around." That this is not for me or this is for me. But at any rate, as always, it's a pleasure, isn't it? Every time we do this, it's like we just say, "Wow." Because we're looking at newspaper clippings and we're looking at whatever, and even though I was on the campus then, I wasn't thinking about. You know, with all the little kids and family and new professor. And wow, I was just in over my head. I had never done any teaching before. But we're just so amazed at the lives of--that why we want to kind of bring this bit of history back. Because there's a richness there that is going to be lost. Already there are people from your era that are gone. So we're wanting to be able to get first hand. Because there's no way that we could learn what you said, right, without you telling us. And maybe we find somebody else who's going to tell us, but we can't find that in any of our archives. We can't find that. So we appreciate you giving the time. And I hope you, if you do come back, get back down to San Antonio, that you'll make a point of letting me know and letting us know so we can see you. [END INTERVIEW]"]
const strpar=props.transcriptstring;
  function chunkString (str, len) {
    const size=Math.ceil(str.length/len);
    const r=Array(size);
    let offset=0;
    for (let i=0;i<size;i++){
      r[i]=str.substr(offset,len)
      offset+=len;
    }
    return r;
  }
  const resultc=chunkString(strpar,496);
  console.log(resultc);

There are total 496 rows in ptr object where some text in the first 0-97 rows some text in the 97-186 rows and so on like that what i am trying to do is to parse the strpar string into total 496 rows like that:
Introduction 0-97 rows text Technical Discussion 97-186 rows text Abstract 186-286 rows text Description 286-380 rows text Output 380-433 rows text Conclusion 433-496 rows text
kindly help me out i am stucked here for many days.

Is it possible to connect an html form with an online database website?

Is it possible to connect an html form with an online database website? I found the code below with the use of php but, my sql database is on a company website so, I cannot use localhost. Is there any other way to connect the html form with the url database? So, what I want to achieve is for customers to complete my form and then the data will be automatically updated in the database. Thank you in advance!

$con = mysqli_connect(“localhost”,”your_localhost_database_user”,”your_localhost_database_password”,”your_localhost_database_db”);