Code Monkey home page Code Monkey logo

serverless-nuxt's Introduction

Serverless Nuxt Plugin

Build Downloads Version License
dependencies Status devDependencies Status

Nuxt on AWS(Lambda + S3) with Serverless Framework.

Demo

Installation

Installation is done using the npm install command:

npm i nuxt-aws-lambda
npm i serverless serverless-nuxt-plugin -D

Check out our complete installation guide to setting up your project.

Documents

Options

custom:
  nuxt:
    version: v${file(./package.json):version}
    bucketName: my-nuxt-project-${self:provider.stage}
    cdnPath:
    assetsPath:
    assetsCacheMaxAge:
Name Description Default
version (required) version
bucketName (required) AWS S3 Bucket Name for static files
cdnPath CDN Path. If this value is not set, the default S3 route(https://${config.bucketName}.s3.amazonaws.com) is used. null
assetsPath Path of assets created after nuxt build. ".nuxt/dist/client"
assetsCacheMaxAge CacheControl MaxAge to use when uploading assets to S3. Using ms. 365d

serverless-nuxt's People

Contributors

andrea-cristaudo avatar ferdinandfrank avatar ffxsam avatar mz3 avatar renovate-bot avatar renovate[bot] avatar steadymoka avatar wan2land 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

Watchers

 avatar  avatar  avatar  avatar

serverless-nuxt's Issues

Should ACL option be excluded if cdnPath is specified?

S3 buckets behind a CDN don't need public read access at all. So when I try to deploy to my S3 bucket, I get "access denied" because the putObject call is doing ACL: 'public-read'.

There's also another bug where if you specify a cdnPath like this:

cdnPath: https://cdn.site.org/subfolder

the files get put at the root level in the S3 bucket, e.g. v1.0/file1.js rather than subfolder/v1.0/file1.js.

I'm happy to open PRs for these.

Feature suggestion: A way to bypass the Nuxt build

In some cases, the deployment to AWS fails, and so we don't want to go through the Nuxt build process again. It would be cool if there were some way to pass a flag (not sure if sls deploy lets you do this) so that the plugin skips the Nuxt build.

Nuxt build process goes into infinite loop

I've just upgraded from Serverless Framework v2 to v3. Now I'm unable to deploy our Nuxt app (see video below). Is this plugin not compatible with Serverless v3?

CleanShot.2022-03-28.at.14.22.28.mp4

Can't serve static files from /static folder

It seems like files (images, robots.txt, ...) can't be served from the Lambda and the API gateway that is located in the Nuxt project's /static folder.
E.g., I do have a valid robots.txt file located in /static/robots.txt that can be served locally using npm run dev:
image

But in production only a random string is being send:
image

The same applies for any image located in the /static folder.
Can someone reproduce the issue or did I miss a step in the setup?

Cannot load JS file

Loading failed for the <script> with source โ€œhttps://aws-xxx-003-dev.s3.amazonaws.com/v0.0.1-alpha/469b3fd99b54ef897cae.jsโ€. login:14:1
Loading failed for the <script> with source โ€œhttps://aws-xxx-003-dev.s3.amazonaws.com/v0.0.1-alpha/e16c041dab9ddcaeb8b5.jsโ€. login:14:1
downloadable font: download failed (font-family: "Material Design Icons" style:normal weight:400 stretch:100 src index:1): status=2152398850 source: https://aws-xxx-003-dev.s3.amazonaws.com/v0.0.1-alpha/fonts/d006653.woff2
Loading failed for the <script> with source โ€œhttps://aws-xxx-003-dev.s3.amazonaws.com/v0.0.1-alpha/744b1393911999f725fb.jsโ€. login:14:1
Loading failed for the <script> with source โ€œhttps://aws-xxx-003-dev.s3.amazonaws.com/v0.0.1-alpha/e16c041dab9ddcaeb8b5.jsโ€. login:14:1
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://aws-xxx-003-dev.s3.amazonaws.com/v0.0.1-alpha/fonts/f511123.ttf. (Reason: CORS request did not succeed).

downloadable font: download failed (font-family: "Material Design Icons" style:normal weight:400 stretch:100 src index:1): status=2152398868 source: https://aws-xxx-003-dev.s3.amazonaws.com/v0.0.1-alpha/fonts/d006653.woff2
Loading failed for the <script> with source โ€œhttps://aws-xxx-003-dev.s3.amazonaws.com/v0.0.1-alpha/469b3fd99b54ef897cae.jsโ€. login:14:1
Loading failed for the <script> with source โ€œhttps://aws-xxx-003-dev.s3.amazonaws.com/v0.0.1-alpha/744b1393911999f725fb.jsโ€. login:14:1
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://aws-xxx-003-dev.s3.amazonaws.com/v0.0.1-alpha/fonts/f511123.ttf. (Reason: CORS request did not succeed).

And other issue:

  • Load file slowly too

Screen Shot 2020-04-13 at 10 20 27 AM

tailwind.config.js

const pkg = require("./package.json")

// require('dotenv').config()
module.exports = {
  mode: 'universal',
  /*
   ** Headers of the page
   */

  head: {
    title: 'xxx',
    meta: [
      { charset: 'utf-8' },
      { name: 'viewport', content: 'width=device-width, initial-scale=1' }

    ],
    link: [{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }],

  },
  /*
   ** Customize the progress-bar color
   */
  loading: '~/components/core/loading.vue',
  /*
   ** Global CSS
   */
  css: [
    '@mdi/font/css/materialdesignicons.css',
    '~/assets/scss/main.scss',
    '~/assets/css/ui-theme/theme/index.css',
  ],
  /*
   ** Plugins to load before mounting the App
   */
  plugins: [
    '~/plugins/element-ui.js',
    '~/plugins/EventBus.js',
    '~/plugins/axios',
    '~/plugins/vue-lodash.js',
    '~/plugins/vue-js-modal.js',
    '@/plugins/vue2-filters',
    {
      src: '~/plugins/vue-line-clamp.js',
      ssr: false
    },
    {
      src: '~/plugins/vue-lazyload.js',
      ssr: true
    },
    {
      src: '~/plugins/vue-zoom-on-hover.js',
      ssr: true
    },
    {
      src: '~/plugins/vue-star-rating.js',
      ssr: false
    },
    {
      src: '~/plugins/vue-moment.js',
      ssr: true
    },
    {
      src: '~/plugins/vue-country-flag.js',
      ssr: false
    },
    {
      src: '~/plugins/vuex-persistedstate.js',
      ssr: false
    },
    {
      src: '~/plugins/load-image.js',
      ssr: true
    },
    {
      src: '~/plugins/my-tracking.js',
      ssr: false
    },
    {
      src: '~/plugins/vue-countdown.js',
      ssr: false
    },
    {
      src: '~/plugins/vue-read-more.js',
      ssr: false
    },
    {
      src: '~/plugins/vue-carousel.js',
      ssr: false
    }
  ],
  /*
   ** Nuxt.js dev-modules
   */
  buildModules: [
    // Doc: https://github.com/nuxt-community/eslint-module
    // ['@nuxtjs/eslint-module', { fix: true }],
    // Doc: https://github.com/nuxt-community/nuxt-tailwindcss
    '@nuxtjs/tailwindcss'
  ],
  /*
   ** Nuxt.js modules
   */
  modules: [
    '@nuxtjs/axios',
    '@nuxtjs/pwa',
    '@nuxtjs/auth',
    '@nuxtjs/sitemap',
    ['@nuxtjs/google-tag-manager', { id: 'GTM-xxxx' }]
  ],


  sitemap: {

    path: '/sitemapindex.xml',
    sitemaps: [
      {
        exclude: [
          '/shopcart/**',
          '/login',
        ],
        path: '/sitemap-home.xml',
        routes: [
          '/',
          '/wholesale'
        ],
        defaults: {
          changefreq: 'daily',
          priority: 1,
          lastmod: new Date(),
          lastmodrealtime: true
        },
      }
    ]

  },

  purgeCSS: {
    whitelistPatterns: [/el-.+$/],
    whitelistPatternsChildren: [/el-.+$/]
  },

  axios: {
    baseURL: 'https://api.xxx.com/api'
  },
  auth: {
    redirect: {
      logout: '/login',
      login: '/login',
    },
    rewriteRedirects: true,
    fullPathRedirect: true,

    strategies: {
      local: {
        endpoints: {
          login: { url: '/user/login', method: 'post', propertyName: 'token' },
          user: { url: '/user/me', method: 'get', propertyName: 'user' },
          logout: { url: '/user/logout', method: 'get' }
        },
        tokenRequired: true,
        tokenType: 'bearer'
      }
    }
  },

  /*
   ** Build configuration
   */
  build: {
    transpile: [/^element-ui/],
    /*
     ** You can extend webpack config here
     */
    extend(config, ctx) {


    }
  }
}

serverless.yml

service:
  name: aws-xxx-serverless-003

plugins:
  - serverless-nuxt-plugin

resources:
  Resources:
    AssetsBucket:
      Type: AWS::S3::Bucket
      Properties:
        BucketName: ${self:custom.nuxt.bucketName}
        CorsConfiguration:
          CorsRules:
            - AllowedMethods:
              - GET
              - HEAD
              AllowedOrigins:
              - "*"

provider:
  name: aws
  region: us-east-1 # this field is used for the assets files s3 path.
  stage: ${opt:stage, 'dev'}
  runtime: nodejs12.x
  environment:
    NODE_ENV: ${file(.env.${self:provider.stage}.yml):NODE_ENV}

custom:
  nuxt:
    version: v0.0.1-alpha
    # If the version is defined in the `package.json` file
    # version: v${file(./package.json):version}
    bucketName: aws-xxx-003-${self:provider.stage}

functions:
  nuxt:
    handler: handler.render
    events:
      # warm up
      # - schedule: rate(5 minutes)
      - http: ANY /
      - http: ANY /{proxy+}

package.json

{
  "name": "frontend_sh001",
  "version": "1.0.0",
  "description": "My tiptop Nuxt.js project",
  "author": "tomtony",
  "private": true,
  "scripts": {
    "dev": "nuxt",
    "build": "nuxt build",
    "start": "nuxt start",
    "generate": "nuxt generate",
    "lint": "eslint --ext .js,.vue --ignore-path .gitignore .",
    "lintfix": "eslint --fix --ext .js,.vue --ignore-path .gitignore ."
  },
  "lint-staged": {
    "*.{js,vue}": "eslint"
  },
  "dependencies": {
    "@chenfengyuan/vue-countdown": "^1.1.5",
    "@mdi/font": "^4.9.95",
    "@nuxtjs/auth": "^4.9.0",
    "@nuxtjs/axios": "^5.9.7",
    "@nuxtjs/google-tag-manager": "^2.3.2",
    "@nuxtjs/pwa": "^3.0.0-beta.20",
    "@nuxtjs/robots": "^2.4.2",
    "@nuxtjs/sentry": "^3.3.1",
    "@nuxtjs/sitemap": "^2.2.0",
    "aws-serverless-express": "^3.3.8",
    "element-ui": "^2.13.0",
    "fastify": "^2.13.1",
    "fastify-static": "^2.6.0",
    "lodash": "^4.17.15",
    "nuxt-start": "^2.12.2",
    "serverless-nuxt": "^1.1.1",
    "vue": "^2.6.11",
    "vue-carousel": "^0.18.0",
    "vue-country-flag": "^1.3.1",
    "vue-js-modal": "^1.3.33",
    "vue-lazyload": "^1.3.3",
    "vue-line-clamp": "^1.3.2",
    "vue-lodash": "^2.1.2",
    "vue-moment": "^4.1.0",
    "vue-read-more": "^1.1.1",
    "vue-star-rating": "^1.6.1",
    "vue-stripe-elements-plus": "^0.3.2",
    "vue2-filters": "^0.8.0",
    "vuex-map-fields": "^1.4.0",
    "vuex-persistedstate": "^2.7.1"
  },
  "devDependencies": {
    "@nuxtjs/dotenv": "^1.4.1",
    "@nuxtjs/eslint-config": "^1.0.1",
    "@nuxtjs/eslint-module": "^1.0.0",
    "@nuxtjs/tailwindcss": "^1.4.0",
    "babel-eslint": "^10.1.0",
    "eslint": "^6.8.0",
    "eslint-config-prettier": "^4.1.0",
    "eslint-plugin-nuxt": "^0.5.2",
    "eslint-plugin-prettier": "^3.1.2",
    "husky": "^2.6.0",
    "lint-staged": "^8.2.1",
    "node-sass": "^4.13.1",
    "nuxt": "^2.12.2",
    "prettier": "^1.19.1",
    "sass-loader": "^8.0.2",
    "serverless": "^1.63",
    "serverless-apigw-binary": "^0.4.4",
    "serverless-nuxt-plugin": "^1.1",
    "serverless-offline": "^6.1.4"
  }
}

@wan2land Could you help me?
Thanks

nuxt-link and imports are not considering stage path `/dev`

When I click a nuxt-link, I get redirected to the rootpath plus nuxt-link.to and it is removing the /dev stage path

Same happens to client imports

GET https://XXXX.execute-api.us-east-1.amazonaws.com/_nuxt/6dbafefff73a2f76381d.js net::ERR_ABORTED 403

Cannot find module 'nuxt-purgecss'

Hi,
I'm able to deploy a brand new nuxt.js project. However, when I try to deploy a project using purgecss, I'm getting this error from CloudWatch: Cannot find module 'nuxt-purgecss'.

Any idea what that can be?

nuxt.config.js

module.exports = {
  mode: "universal",
  /*
   ** Headers of the page
   */
  head: {
    title: process.env.APP_NAME,
    meta: [
      { charset: "utf-8" },
      { name: "viewport", content: "width=device-width, initial-scale=1" },
      {
        hid: "description",
        name: "description",
        content: process.env.npm_package_description || ""
      }
    ],
    link: [{ rel: "icon", type: "image/x-icon", href: "/favicon.ico" }]
  },
  /*
   ** Customize the progress-bar color
   */
  loading: { color: "#fff" },
  /*
   ** Global CSS
   */
  css: ["~/assets/sass/tailwind.sass"],
  /*
   ** Plugins to load before mounting the App
   */
  plugins: [
    "./plugins/global.js",
    "./plugins/mixins/responsive.js",
    "./plugins/sbkl-client.js"
  ],
  /*
   ** Nuxt.js dev-modules
   */
  buildModules: [],
  /*
   ** Nuxt.js modules
   */
  modules: [
    "@nuxtjs/axios",
    "@nuxtjs/dotenv",
    "@nuxtjs/auth",
    "portal-vue/nuxt",
    "nuxt-purgecss"
  ],
  /*
   ** Build configuration
   */
  build: {
    /*
     ** You can extend webpack config here
     */
    extractCSS: true,
    postcss: {
      plugins: {
        tailwindcss: path.resolve(__dirname, "./tailwind.config.js")
      }
    },
    transpile: ["sbkl-client"],
    extend(config, ctx) {}
  },
  purgeCSS: {
    mode: "postcss",
    paths: ["node_modules/sbkl-client/**/*.vue", "admin.config.js"]
  }
};

Package.json

  "dependencies": {
    "@nuxtjs/auth": "^4.9.0",
    "@nuxtjs/axios": "^5.3.6",
    "@nuxtjs/dotenv": "^1.4.0",
    "@popperjs/core": "^2.1.0",
    "nuxt-start": "^2.11.0",
    "portal-vue": "^2.1.7",
    "sbkl-client": "^1.0.1",
    "serverless-nuxt": "^1.1.1"
  },
  "devDependencies": {
    "@tailwindcss/ui": "^0.1.3",
    "node-sass": "^4.13.1",
    "nuxt": "^2.11.0",
    "nuxt-purgecss": "^0.2.1",
    "sass-loader": "^8.0.2",
    "serverless-domain-manager": "^3.3.1",
    "serverless-nuxt-plugin": "^1.1.0",
    "tailwindcss": "^1.2.0"
  }

Access Denied error with no details

Hi,

Our deploy process is suddenly failing, with no changes made on our end. Running SLS_DEBUG=1 sls deploy --stage prod, this is the last bit of the output:

Serverless: Invoke aws:deploy:deploy
Serverless: Uploading CloudFormation file to S3...
Serverless: Uploading artifacts...
Serverless: Uploading service presentation.zip file to S3 (25.99 MB)...
Serverless Nuxt Plugin: after upload artifacts
Serverless Nuxt Plugin: upload asset files

 Access Denied -------------------------------------------

  AccessDenied: Access Denied
      at Request.extractError (/Volumes/SuperData/work/v2-presentation/node_modules/aws-sdk/lib/services/s3.js:714:35)
      at Request.callListeners (/Volumes/SuperData/work/v2-presentation/node_modules/aws-sdk/lib/sequential_executor.js:106:20)
      at Request.emit (/Volumes/SuperData/work/v2-presentation/node_modules/aws-sdk/lib/sequential_executor.js:78:10)
      at Request.emit (/Volumes/SuperData/work/v2-presentation/node_modules/aws-sdk/lib/request.js:688:14)
      at Request.transition (/Volumes/SuperData/work/v2-presentation/node_modules/aws-sdk/lib/request.js:22:10)
      at AcceptorStateMachine.runTo (/Volumes/SuperData/work/v2-presentation/node_modules/aws-sdk/lib/state_machine.js:14:12)
      at /Volumes/SuperData/work/v2-presentation/node_modules/aws-sdk/lib/state_machine.js:26:10
      at Request.<anonymous> (/Volumes/SuperData/work/v2-presentation/node_modules/aws-sdk/lib/request.js:38:9)
      at Request.<anonymous> (/Volumes/SuperData/work/v2-presentation/node_modules/aws-sdk/lib/request.js:690:12)
      at Request.callListeners (/Volumes/SuperData/work/v2-presentation/node_modules/aws-sdk/lib/sequential_executor.js:116:18)
      at Request.emit (/Volumes/SuperData/work/v2-presentation/node_modules/aws-sdk/lib/sequential_executor.js:78:10)
      at Request.emit (/Volumes/SuperData/work/v2-presentation/node_modules/aws-sdk/lib/request.js:688:14)
      at Request.transition (/Volumes/SuperData/work/v2-presentation/node_modules/aws-sdk/lib/request.js:22:10)
      at AcceptorStateMachine.runTo (/Volumes/SuperData/work/v2-presentation/node_modules/aws-sdk/lib/state_machine.js:14:12)
      at /Volumes/SuperData/work/v2-presentation/node_modules/aws-sdk/lib/state_machine.js:26:10
      at Request.<anonymous> (/Volumes/SuperData/work/v2-presentation/node_modules/aws-sdk/lib/request.js:38:9)
      at Request.<anonymous> (/Volumes/SuperData/work/v2-presentation/node_modules/aws-sdk/lib/request.js:690:12)
      at Request.callListeners (/Volumes/SuperData/work/v2-presentation/node_modules/aws-sdk/lib/sequential_executor.js:116:18)
      at callNextListener (/Volumes/SuperData/work/v2-presentation/node_modules/aws-sdk/lib/sequential_executor.js:96:12)
      at IncomingMessage.onEnd (/Volumes/SuperData/work/v2-presentation/node_modules/aws-sdk/lib/event_listeners.js:336:13)
      at IncomingMessage.emit (events.js:412:35)
      at IncomingMessage.emit (domain.js:475:12)
      at endReadableNT (internal/streams/readable.js:1334:12)
      at processTicksAndRejections (internal/process/task_queues.js:82:21)

There's no bucket mentioned, no indication of what the plugin was trying to do. I even ran this using an IAM user that has admin access, and it still failed.

Any idea how I can begin to pinpoint the problem?

Nuxt Serverless with the Nuxt Content Documentation Theme - Cannot use import statement outside a module

Hey @wan2land,

I just wanted to thank you for this amazing plugin, it has so much potential within the Nuxt ecosystem.

I was wondering if you could point me in the right direction.

I'm using your plugin, and trying to deploy the next default Nuxt Content Theme to serverless.

// `nuxt.config.js`
import theme from '@nuxt/content-theme-docs'

module.exports = theme({
  target: 'server',

  docs: {
    primaryColor: '#E24F55'
  },
  loading: { color: '#00CD81' },

  telemetry: false,

  build: {
    // You can extend webpack config here
    transpile: ['@nuxt/content-theme-docs'],
  },
})

When running serverless deploy, I'm seeing the following error.

Serverless: Running "serverless" installed locally (in service node_modules)
Serverless: Deprecation warning: Resolution of lambda version hashes was improved with better algorithm, which will be used in next major release.
            Switch to it now by setting "provider.lambdaHashingVersion" to "20201221"
            More Info: https://www.serverless.com/framework/docs/deprecations/#LAMBDA_HASHING_VERSION_V2
Serverless Nuxt Plugin: build nuxt
 
 Syntax Error --------------------------------------------
 
  /github/workspace/nuxt.config.js:1
  import theme from '@nuxt/content-theme-docs'
  ^^^^^^
  
  SyntaxError: Cannot use import statement outside a module
      at compileFunction (<anonymous>)
      at wrapSafe (internal/modules/cjs/loader.js:979:16)
      at Module._compile (internal/modules/cjs/loader.js:1027:27)
      at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
      at Module.load (internal/modules/cjs/loader.js:928:32)
      at Function.Module._load (internal/modules/cjs/loader.js:769:14)
      at Module.require (internal/modules/cjs/loader.js:952:19)
      at require (internal/modules/cjs/helpers.js:88:18)
      at ServerlessNuxtPlugin.build (/github/workspace/node_modules/serverless-nuxt-plugin/src/index.js:69:22)
      at PluginManager.invoke (/github/workspace/node_modules/serverless/lib/classes/PluginManager.js:552:20)
      at async PluginManager.spawn (/github/workspace/node_modules/serverless/lib/classes/PluginManager.js:574:5)
      at async Object.before:deploy:deploy [as hook] (/github/workspace/node_modules/serverless/lib/plugins/deploy.js:49:11)
      at async PluginManager.invoke (/github/workspace/node_modules/serverless/lib/classes/PluginManager.js:552:9)
      at async PluginManager.run (/github/workspace/node_modules/serverless/lib/classes/PluginManager.js:598:7)
      at async Serverless.run (/github/workspace/node_modules/serverless/lib/Serverless.js:313:5)
      at async /usr/local/lib/node_modules/serverless/scripts/serverless.js:634:9
 
     For debugging logs, run again after setting the "SLS_DEBUG=*" environment variable.
 
  Get Support --------------------------------------------
     Docs:          docs.serverless.com
     Bugs:          github.com/serverless/serverless/issues
     Issues:        forum.serverless.com
 
  Your Environment Information ---------------------------
     Operating System:          linux
     Node Version:              14.16.1
     Framework Version:         2.38.0 (local)
     Plugin Version:            4.5.3
     SDK Version:               4.2.2
     Components Version:        3.9.1

I was wondering if you had any ideas on how I might approach this error? Would it be possible to use some type of trickery using require.

Any advice or suggestions would be much appreciated. I've put together a issue repo here.
https://github.com/robmellett/nuxt-documentation-serverless

`cdnPath` on the built seems to not work as expected.

Hi @wan2land hope you're doing great, thanks for the work on this plugin! I'm writing because everything seems to be working fine, but the cdnPath on the built seems to not work as expected.

The weird thing is that in the .nuxt/dist/server/server.js for example the __webpack_public_path__ is properly set but when I navigate to the site (I'm using a custom domain) all the assets seems to be loaded from the /__nuxt/....

Do you have any idea where to look in order to fix this?

I have in the nuxt.config.js:

module.exports = {
  telemetry: false,
  mode: 'universal',
  target: 'server',
  srcDir: 'src/',
  server: {
    port: 4400,
  },
  head: {
    ...
  },
  build: {
    // The "publicPath" value is automatically generated by the serverless-nuxt plug-in
    // If the "publicPath" value is set, delete it.
  },
  buildModules: [
    ['@nuxtjs/google-analytics', { id: 'UA-XXX' }],
    '@nuxtjs/google-fonts',
    '@nuxtjs/tailwindcss',
  ],
}

and in the serverless.yml

service: service-name

frameworkVersion: '2'

plugins:
  - serverless-nuxt-plugin
  - serverless-s3-sync
  - serverless-dotenv-plugin
  - serverless-apigw-binary
  - serverless-offline
  - serverless-domain-manager

package:
  individually: true
  excludeDevDependencies: true
  exclude:
    - src/**
    - .nuxt/**
    - package.json
    - package-lock.json
    - .gitignore
    - .env.example
    - node_modules/**
    - src/static/**
  include:
    - .nuxt/dist/**

provider:
  name: aws
  runtime: nodejs12.x
  lambdaHashingVersion: 20201221
  region: us-east-2
  stage: ${env:STAGE}
  versionFunctions: false
  apiGateway:
    shouldStartNameWithService: true
  environment:
    NODE_ENV: ${env:NODE_ENV}

custom:
  buckets:
    ASSETS_BUCKET_NAME: ${self:service}-${self:provider.stage}
    STATIC_BUCKET_NAME: ${self:service}-static
  apigwBinary:
    types:
      - '*/*'
  serverless-offline:
    noPrependStageInUrl: true
    httpPort: 4400
  customDomain:
    domainName: ${env:DOMAIN}
    basePath: ''
    stage: ${self:provider.stage}
    createRoute53Record: true
  s3Sync:
    - bucketName: ${self:custom.buckets.STATIC_BUCKET_NAME}
      localDir: src/static
      acl: public-read
  nuxt:
    version: v${file(./package.json):version}
    bucketName: ${self:custom.buckets.ASSETS_BUCKET_NAME}
    # cdnPath:
    # assetsPath:
    # assetsCacheMaxAge:

resources:
  Resources:
    AssetsBucket:
      Type: AWS::S3::Bucket
      Properties:
        BucketName: ${self:custom.nuxt.bucketName}
        CorsConfiguration:
          CorsRules:
            - AllowedMethods:
              - GET
              - HEAD
              AllowedOrigins:
              - https://${env:DOMAIN}
    StaticBucket:
      Type: AWS::S3::Bucket
      Properties:
        BucketName: ${self:custom.buckets.STATIC_BUCKET_NAME}
        CorsConfiguration:
          CorsRules:
            - AllowedMethods:
              - GET
              - HEAD
              AllowedOrigins:
              - https://${env:DOMAIN}

functions: ...

Everything is being uploaded correctly, but the rendered site is looking the assets in /__nuxt/..., ๐Ÿค” ๐Ÿ˜ฉ

Any help is appreciate it!! thanks again

Originally posted by @cavi21 in #74 (comment)

Dependencies not removed

What should be the expected content on the zip file under .serverless?

Mine is my full souce โ€“ incluindo everything on node_modules and .nuxt.

Shouldn't it be only .nuxt/dist/client?

My package.json is very lightweight, but the .zip sent to AWS has over 110 MB (because of node_modules)

I tried some custom settings on serverless.yml (like package exlude/include) but everything I get that nuxt-start were not found.

Any suggestions?

issue env when run deploy

Hello @wan2land
I have an issue:
process.env.GOOGLE_TAG_MANAGER_ID and process.env.FACEBOOK_PIXEL_ID return NULL value when run deploy npm run deploy:prod

here my code:
nuxt.config.js

const pkg = require("./package.json")
module.exports = {
  mode: 'universal',
env: {
GOOGLE_TAG_MANAGER_ID: process.env.GOOGLE_TAG_MANAGER_ID,
  FACEBOOK_PIXEL_ID: process.env.FACEBOOK_PIXEL_ID,
},
  modules: [
    'nuxt-facebook-pixel-module',
    ['@nuxtjs/google-tag-manager', { id: process.env.GOOGLE_TAG_MANAGER_ID }],
  ],
  facebook: {
    track: 'PageView',
    pixelId: process.env.FACEBOOK_PIXEL_ID,
    disabled: false
  },
}

.env-cmdrc.js

  prod: {
    FACEBOOK_PIXEL_ID: 'xxxx',
    GOOGLE_TAG_MANAGER_ID: 'xxxx',
}

Error:

{
    "errorType": "Runtime.UnhandledPromiseRejection",
    "errorMessage": "Error: The `pixelId` option is required.",
    "reason": {
        "errorType": "Error",
        "errorMessage": "The `pixelId` option is required.",
        "stack": [
            "Error: The `pixelId` option is required.",
            "    at ModuleContainer.facebookPixelModule (/var/task/node_modules/nuxt-facebook-pixel-module/lib/module.js:13:31)",
            "    at ModuleContainer.addModule (/var/task/node_modules/@nuxt/core/dist/core.js:215:34)",
            "    at /var/task/node_modules/@nuxt/utils/dist/utils.js:1803:43",
            "    at async ModuleContainer.ready (/var/task/node_modules/@nuxt/core/dist/core.js:43:5)",
            "    at async Nuxt._init (/var/task/node_modules/@nuxt/core/dist/core.js:685:5)"
        ]
    },
    "promise": {},
    "stack": [
        "Runtime.UnhandledPromiseRejection: Error: The `pixelId` option is required.",
        "    at process.<anonymous> (/var/runtime/index.js:35:15)",
        "    at process.emit (events.js:310:20)",
        "    at processEmit [as emit] (/var/task/node_modules/signal-exit/index.js:161:32)",
        "    at processPromiseRejections (internal/process/promises.js:209:33)",
        "    at processTicksAndRejections (internal/process/task_queues.js:98:32)"
    ]
}

serverless.yml can't get environment variable

Hello!
First of all, thank you for the nice and complete tutorial. Absolutely new to serverless here and it was very helpful.

When trying to deploy I received:

  Access Denied ------------------------------------------
 
  AccessDenied: Access Denied

Running SLS_DEBUG=1 serverless deploy shows that:

 Serverless Warning --------------------------------------

  A valid environment variable to satisfy the declaration 'env:NODE_ENV' could not be found.
 
 Serverless Warning --------------------------------------
 
  A valid environment variable to satisfy the declaration 'env:API_URL' could not be found.
 
 Serverless Warning --------------------------------------
 
  A valid environment variable to satisfy the declaration 'env:DOMAIN_NAME' could not be found.
 
 (...)

My files:

.env-cmdrc

module.exports = {
  local: {
    NODE_ENV: 'development',
    PORT: '8080',
    API_URL: 'http://localhost:8080/api',
  },
  prod: {
    DOMAIN_NAME: 'app.domain.com',
    NODE_ENV: 'production',
    NUXT_TELEMETRY_DISABLED: '1',
    API_URL: 'https://domain.com/api',
  },
}

serverless.yml

provider:
  name: aws
  region: us-east-1
  stage: ${opt:stage, 'dev'}
  runtime: nodejs12.x
  environment:
    NODE_ENV: ${env:NODE_ENV}
    API_URL: ${env:API_URL}

On serverless.yml if I change the variables to strings it works. For example: 'production' instead of ${env:NODE_ENV}.

Perhaps my .env-cmdrc is not "discoverable"?
To deploy I am using env-cmd -e prod sls deploy --stage prod

[HELP] error undefined

Hello @wan2land
The before days, my website working well. But Today, It's not working.
Error Internal server error for all website serverless deployed.

Issue after refreshing page on route

Hey guys,

I just followed the documentation and deployed my service, worked like a charm. But if I hit refresh when inside a route, all the js files and images returns 404. Any hint on what I should do?

This is my nuxt config file, everything else is the same as in the read me.

module.exports = {
	baseUrl: process.env.BASE_URL || "http://localhost:3000",
	components: true,
	head: {
		titleTemplate: " %s",
		htmlAttrs: {
			Lang: "en",
		},
		bodyAttrs: {
			class: ["sidebar-main-active right-column-fixed"],
		},
		meta: [
			{
				charset: "utf-8",
			},
			{
				name: "viewport",
				content: "width=device-width, initial-scale=1, shrink-to-fit=no"
			},
		],
		link: [
			{
				rel: "stylesheet",
				href:
					"https://cdn.jsdelivr.net/npm/[email protected]/fonts/remixicon.css",
			},
			{
				rel: "stylesheet",
				href:
					"https://maxst.icons8.com/vue-static/landings/line-awesome/line-awesome/1.3.0/css/line-awesome.min.css",
			},
		],
		script: [
			{
				type: "text/javascript",
				body: true,
				src: "js/jquery.min.js",
			},
			{ type: "text/javascript", body: true, src: "js/popper.min.js" },
			{
				type: "text/javascript",
				body: true,
				src: "js/bootstrap.min.js",
			},
			{
				type: "text/javascript",
				body: true,
				src: "js/countdown.min.js",
			},
			{
				type: "text/javascript",
				body: true,
				src: "js/waypoints.min.js",
			},
			{
				type: "text/javascript",
				body: true,
				src: "js/jquery.counterup.min.js",
			},
			{
				type: "text/javascript",
				body: true,
				src: "js/wow.min.js",
			},
			// {
			// 	type: "text/javascript",
			// 	body: true,
			// 	src: "js/apexcharts.min.js",
			// },
			{
				type: "text/javascript",
				body: true,
				src: "js/slick.min.js",
			},
			{
				type: "text/javascript",
				body: true,
				src: "js/select2.min.js",
			},
			{
				type: "text/javascript",
				body: true,
				src: "js/owl.carousel.min.js",
			},
			{
				type: "text/javascript",
				body: true,
				src: "js/jquery.magnific-popup.min.js",
			},
			{
				type: "text/javascript",
				body: true,
				src: "js/smooth-scrollbar.js",
			},
			{
				type: "text/javascript",
				body: true,
				src: "js/lottie.js",
			},
			{
				type: "text/javascript",
				body: true,
				src: "js/core.js",
			},
			{
				type: "text/javascript",
				body: true,
				src: "js/charts.js",
			},
			{
				type: "text/javascript",
				body: true,
				src: "js/animated.js",
			},
			{
				type: "text/javascript",
				body: true,
				src: "js/kelly.js",
			},
			{
				type: "text/javascript",
				body: true,
				src: "js/maps.js",
			},
			{
				type: "text/javascript",
				body: true,
				src: "js/worldLow.js",
			},
			{
				type: "text/javascript",
				body: true,
				src: "js/chart-custom.js",
			},
			{
				type: "text/javascript",
				body: true,
				src: "js/custom.js",
			},
		],
	},
	router: {
		prefetchLinks: true,
	},
	plugins: [
		"~/plugins/dataApi",
	],
	modules: [],
	css: [
		"~/assets/css/animate.css",
		"~/assets/css/bootstrap.min.css",
		"~/assets/css/Chart.min.css",
		"~/assets/css/developer.css",
		"~/assets/css/dripicons.css",
		"~/assets/css/flatpickr.min.css",
		"~/assets/css/fontawesome.css",
		"~/assets/css/ionicons.min.css",
		"~/assets/css/magnific-popup.css",
		"~/assets/css/owl.carousel.min.css",
		"~/assets/css/responsive.css",
		"~/assets/css/select2.min.css",
		"~/assets/css/slick.css",
		"~/assets/css/typography.css",
		"~/assets/css/style.css",
		"~/assets/css/variable.css",
	],
	build: {
		extractCSS: true,
		loaders: {
			limit: 0,
		},
		publicPath: process.env.SERVERLESS_NUXT_PUBLIC_PATH,
	},
};

Getting 404 all the time

I am getting 404, on any page. I know for example login exists. I was asking my self is serverless-nuxt can be used with universal and not just spa?

resolved path for assets is wrong

It seems like there is an issue with resolving the correct path for the deployed assets. In my first test my site loads but all the linked resources (css, js) point to the wrong location.

https://s3.undefined.amazonaws.com/myproject-dev/v0.0.1/a6b369ff4ddca0b87aeb.js
seems like we have some undefined var somewhere, any idea where this could come from?

shouldn't the link be something like this anyways?
https://myproject-dev.s3.amazonaws.com/v0.0.1/a6b369ff4ddca0b87aeb.js

Asset files not automatically uploading to S3 bucket

Hello, I attempted to follow the instructions here and deploy a site using this but I'm having an issue with any of my static assets loading. it seems only the favicon is loading on the site and not of the images I've placed. It also seems like some of my styling is not correctly loaded but everything works fine in DEV. My assumption is I'm doing something wrong with the CDN. Can anyone take a look and let me know if I've done this correctly?
https://github.com/Battle-Line-Productions/battlesite-home

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Warning

These dependencies are deprecated:

Datasource Name Replacement PR?
npm @babel/plugin-proposal-class-properties Unavailable
npm @babel/plugin-proposal-object-rest-spread Unavailable

Rate-Limited

These updates are currently rate-limited. Click on a checkbox below to force their creation now.

  • chore(deps): update dependency @types/aws-serverless-express to v3.3.9
  • chore(deps): update dependency @types/express to v4.17.21
  • fix(deps): update dependency chalk to v4.1.2
  • fix(deps): update dependency mime-types to v2.1.35
  • chore(deps): update dependency eslint-config-stable to v0.10.0
  • chore(deps): update dependency nuxt to v2.17.4
  • fix(deps): update dependency @vendia/serverless-express to v4.12.6
  • chore(deps): update actions/checkout action to v4
  • chore(deps): update actions/setup-node action to v4
  • chore(deps): update dependency @types/node to v20
  • chore(deps): update dependency eslint to v9
  • chore(deps): update dependency husky to v9
  • chore(deps): update dependency lerna to v8
  • chore(deps): update dependency nuxt to v3
  • chore(deps): update dependency rimraf to v5
  • chore(deps): update dependency typescript to v5
  • chore(deps): update jest monorepo to v29 (major) (@types/jest, jest, ts-jest)
  • ๐Ÿ” Create all rate-limited PRs at once ๐Ÿ”

Edited/Blocked

These updates have been manually edited so Renovate will no longer make changes. To discard all commits and start over, click on a checkbox.

Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

Detected dependencies

github-actions
.github/workflows/nodejs.yml
  • actions/checkout v2
  • actions/setup-node v1
npm
package.json
  • @babel/cli 7.15.7
  • @babel/core 7.15.5
  • @babel/plugin-proposal-class-properties 7.14.5
  • @babel/plugin-proposal-object-rest-spread 7.15.6
  • @babel/preset-env 7.15.6
  • @babel/preset-typescript 7.15.0
  • @commitlint/cli 13.1.0
  • @commitlint/config-conventional 13.1.0
  • @types/aws-lambda 8.10.83
  • @types/aws-serverless-express 3.3.5
  • @types/express 4.17.13
  • @types/jest 27.0.2
  • @types/node 14.17.19
  • eslint 7.32.0
  • eslint-config-stable 0.9.0
  • husky 7.0.2
  • jest 27.2.2
  • lerna 4.0.0
  • nuxt 2.15.8
  • rimraf 3.0.2
  • ts-jest 27.0.5
  • typescript 4.4.3
packages/nuxt-aws-lambda/package.json
  • @vendia/serverless-express ^4.3.4
packages/serverless-nuxt-plugin/package.json
  • chalk ^4.0.0
  • mime-types ^2.1.24
  • ms ^2.1.2

  • Check this box to trigger a request for Renovate to run again on this repository

Nuxt PWA module not working

I'm currently trying to integrate the Nuxt PWA Module into my application.
Everything is working fine locally, but when I deploy it via the serverless-nuxt package the plugin does not seem to work as no service worker and no manifest.json file is found.

Did anyone already manage to integrate it successfully?

I cannot call the api via axios

Hello @wan2land
I cannot call the api via axios
axios.js plugins

import { showError } from '@/common/AppUtils.js'

export default function({ $axios, redirect, store, app }) {
  $axios.setHeader('Content-Type', 'application/json')
  $axios.onRequest((config) => {
    if (app.$auth.getToken('local')) {
      config.headers.common.Authorization = app.$auth.getToken('local')
    }
  })
  $axios.onError((error) => {
    const code = parseInt(error.response && error.response.status)
    if (code === 401) {
      app.$auth.logout()
    } else {
      showError(error.response.data.message)
    }
    return Promise.reject(error)
  })
}

Index.vue

  async asyncData({ app, $axios, error }) {
    try {
      // console.log(app.$device)
      const todaySuggestionProducts = await $axios.$get(
        '/products'
      )

nuxt.config.js

  axios: {
    baseURL: process.env.API_URL
  },

Error:

13:06:39
2020-04-28T13:06:39.174Z ba79c228-4fba-4e6e-af87-2bc4889d031c INFO TypeError: Cannot read property 'data' of undefined at server.js:1:595274 at server.js:1:593957 at processTicksAndRejections (internal/process/task_queues.js:97:5) at async asyncData (9b81432fb5e8a30cf197.js:1:32789)
2020-04-28T13:06:39.174Z	ba79c228-4fba-4e6e-af87-2bc4889d031c	INFO	TypeError: Cannot read property 'data' of undefined
    at server.js:1:595274
    at server.js:1:593957
    at processTicksAndRejections (internal/process/task_queues.js:97:5)
    at async asyncData (9b81432fb5e8a30cf197.js:1:32789)

Can't authenticate users on SSR

Once more, thanks for this awesome package.

I just noticed that the authentication of logged users won't work for SSR. If I'm on a protected page with an authenticated user within my Nuxt application and I reload the page, I will be redirected to the login page as my middleware defines it.
I'm using the official https://auth.nuxtjs.org/ module which relies on cookies when authorizing users for SSR. Therefore, I guess the client's cookies can not be read within the Lambda function.
Can anyone reproduce the issue?
Maybe we need to add the express cookie parser package to solve the problem?

This is the code of my login middleware which fails on the server side:

export default function ({ store, redirect }) {
    if (!store.state.auth.loggedIn) {
        return redirect('/login');
    }
}

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.