Baroshem / nuxt-newsletter

✉️ Nuxt module for first class integration with popular newsletter providers
https://nuxt-newsletter.netlify.app/
MIT License
57 stars 7 forks source link

Provide a custom url for subscribing #7

Open Baroshem opened 2 years ago

Baroshem commented 2 years ago

This feature is a recommendation based on the conversation on Twitter. (https://twitter.com/GwynHockridge/status/1546580353292402689?s=20&t=HCbpzfd3xAMxQr71EOkBhg)

Gwyn recommended to implement a feature when a user can define an url where the request will be sent from the frontend instead of localhost to handle the subscription.

The use case is a static application that does not have a server middleware but the users would still want to be able to add to newsletter.

The implementation could look like this:

import { defineNuxtConfig } from 'nuxt'

export default defineNuxtConfig({
  ssr: false,
  modules: ['nuxt-newsletter'],
  newsletter: {
    url: 'https://my-custom-server.com'
  }
})

After setting the url property, useNewsletterSubscribe composable will instead send a request to that url and await for the response:

import { useRuntimeConfig } from '#imports'

export async function useNewsletterSubscribe(email: string) {
  const newsletterConfig = useRuntimeConfig().newsletter

  return await $fetch(newsletterConfig.url || '/api/newsletter/subscribe', {
    body: { email },
    method: 'POST'
  }).catch(e => e.data);
gwynhokkers commented 2 years ago

Looks good. Just want to clarify, if I set newsletter.url to a env variable that is undefined - it would then try and use the nuxt server middleware by default? Thinking of how to set env variables so that, in development, we can use SSR mode and the server middleware. But in production we use the custom api.

Baroshem commented 2 years ago

You could then try something like this:

import { defineNuxtConfig } from 'nuxt'

export default defineNuxtConfig({
  ssr: false,
  modules: ['nuxt-newsletter'],
  newsletter: process.env.NODE_ENV === 'development' ? { revue: {  apiKey: '123', component: true } } : { url: 'https://my-custom-server.com' }
})